use select to detect new incoming connections

This commit is contained in:
Benjamin Sergeant 2019-01-01 22:21:07 -08:00
parent 1bc5bc7f1c
commit b95e5e36dc
2 changed files with 22 additions and 9 deletions

View File

@ -152,25 +152,38 @@ namespace ix
// Set the socket to non blocking mode, so that accept calls are not blocking // Set the socket to non blocking mode, so that accept calls are not blocking
SocketConnect::configure(_serverFd); SocketConnect::configure(_serverFd);
// Return value of std::async, ignored
std::future<void> f; std::future<void> f;
// Select arguments
fd_set rfds;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 10 * 1000; // 10ms
for (;;) for (;;)
{ {
if (_stop) return; if (_stop) return;
FD_ZERO(&rfds);
FD_SET(_serverFd, &rfds);
select(_serverFd + 1, &rfds, nullptr, nullptr, &timeout);
if (!FD_ISSET(_serverFd, &rfds))
{
// We reached the select timeout, and no new connections are pending
continue;
}
// Accept a connection. // Accept a connection.
struct sockaddr_in client; // client address information struct sockaddr_in client; // client address information
int clientFd; // socket connected to client int clientFd; // socket connected to client
socklen_t addressLen = sizeof(socklen_t); socklen_t addressLen = sizeof(socklen_t);
memset(&client, 0, sizeof(client));
if ((clientFd = accept(_serverFd, (struct sockaddr *)&client, &addressLen)) < 0) if ((clientFd = accept(_serverFd, (struct sockaddr *)&client, &addressLen)) < 0)
{ {
if (errno == EWOULDBLOCK) if (errno != EWOULDBLOCK)
{
std::chrono::duration<double, std::milli> wait(10);
std::this_thread::sleep_for(wait);
}
else
{ {
// FIXME: that error should be propagated // FIXME: that error should be propagated
std::stringstream ss; std::stringstream ss;

View File

@ -83,7 +83,7 @@ namespace
void WebSocketChat::start() void WebSocketChat::start()
{ {
std::string url("ws://localhost:8080/"); std::string url("ws://localhost:8090/");
_webSocket.setUrl(url); _webSocket.setUrl(url);
std::stringstream ss; std::stringstream ss;
@ -232,9 +232,9 @@ TEST_CASE("Websocket chat", "[websocket_chat]")
{ {
ix::setupWebSocketTrafficTrackerCallback(); ix::setupWebSocketTrafficTrackerCallback();
int port = 8080; int port = 8090;
ix::WebSocketServer server(port); ix::WebSocketServer server(port);
startServer(server); REQUIRE(startServer(server));
std::string session = ix::generateSessionId(); std::string session = ix::generateSessionId();
WebSocketChat chatA("jean", session); WebSocketChat chatA("jean", session);