unittest pass

This commit is contained in:
Benjamin Sergeant
2019-01-01 13:47:25 -08:00
parent 58a68ec0be
commit 5ea2028c22
3 changed files with 42 additions and 10 deletions

View File

@ -9,6 +9,7 @@
#include "IXWebSocket.h"
#include <sstream>
#include <future>
#include <netdb.h>
#include <stdio.h>
@ -100,6 +101,8 @@ namespace ix
void WebSocketServer::run()
{
std::future<void> f;
for (;;)
{
// Accept a connection.
@ -109,12 +112,18 @@ namespace ix
if ((clientFd = accept(_serverFd, (struct sockaddr *)&client, &addressLen)) == -1)
{
// FIXME: that error should be propagated
std::cerr << "WebSocketServer::run() error accepting connection: "
<< strerror(errno);
<< strerror(errno)
<< std::endl;
continue;
}
_workers[clientFd] = std::thread(&WebSocketServer::handleConnection, this, clientFd);
// Launch the handleConnection work asynchronously in its own thread.
//
// the destructor of a future returned by std::async blocks,
// so we need to declare it outside of this loop
f = std::async(std::launch::async, &WebSocketServer::handleConnection, this, clientFd);
}
}
@ -126,14 +135,27 @@ namespace ix
ix::WebSocket webSocket;
_onConnectionCallback(webSocket);
_clients.insert(&webSocket);
webSocket.start();
webSocket.connectToSocket(fd); // FIXME: we ignore the return value
auto status = webSocket.connectToSocket(fd);
if (!status.success)
{
std::cerr << "WebSocketServer::handleConnection() error: "
<< status.errorStr
<< std::endl;
return;
}
// We can probably do better than this busy loop, with a condition variable.
for (;;)
while (webSocket.isConnected())
{
std::chrono::duration<double, std::milli> wait(10);
std::this_thread::sleep_for(wait);
}
_clients.erase(&webSocket);
std::cerr << "WebSocketServer::handleConnection() done" << std::endl;
}
}

View File

@ -8,8 +8,9 @@
#include <utility> // pair
#include <string>
#include <map>
#include <set>
#include <thread>
#include <mutex>
#include <functional>
#include "IXWebSocket.h"
@ -28,6 +29,9 @@ namespace ix
std::pair<bool, std::string> listen();
void run();
// FIXME: need mutex
std::set<WebSocket*> getClients() { return _clients; }
private:
void handleConnection(int fd);
@ -39,6 +43,6 @@ namespace ix
// socket for accepting connections
int _serverFd;
std::map<int, std::thread> _workers;
std::set<WebSocket*> _clients;
};
}