use select to detect new incoming connections

This commit is contained in:
Benjamin Sergeant 2019-01-01 22:21:07 -08:00
parent 0b90f7df1b
commit 6bfabd5493
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
SocketConnect::configure(_serverFd);
// Return value of std::async, ignored
std::future<void> f;
// Select arguments
fd_set rfds;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 10 * 1000; // 10ms
for (;;)
{
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.
struct sockaddr_in client; // client address information
int clientFd; // socket connected to client
socklen_t addressLen = sizeof(socklen_t);
memset(&client, 0, sizeof(client));
if ((clientFd = accept(_serverFd, (struct sockaddr *)&client, &addressLen)) < 0)
{
if (errno == EWOULDBLOCK)
{
std::chrono::duration<double, std::milli> wait(10);
std::this_thread::sleep_for(wait);
}
else
if (errno != EWOULDBLOCK)
{
// FIXME: that error should be propagated
std::stringstream ss;

View File

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