mezo
mezo

Reputation: 453

Non-blocking select()?

I'm trying to implement simple networking game (client - server) which uses UDP to transfer game events over network, and I have this working well, but now I would like to add to game chat over tcp in same console application. I've tried to implement multi client chat using select() and non-blocking master socket. Chat is working as standalone application but I have problems putting it together.

Basically my server loop looks like this:

while(true)
{
    sendUDPdata()
    ...

    while(true)
    {
        receiveUDPdata()
    }
}

Problem is that when I want to add chat to server's main loop (handling UDP) like this:

while(true)
{
    HandleTCPConnections();

    sendUDPdata();
    ...

    while(true)
    {
        receiveUDPdata();
    }
}

calling select() in HandleTCPConnections() blocks whole server. Is there any way how to handle this?

Upvotes: 0

Views: 2909

Answers (2)

edmz
edmz

Reputation: 8494

select is a blocking call if there's no data available from the sockets, in your case.

Your chat can either run along with the server or in parallel with it: you've already got the first case; for the second, you'd better go for a separate thread that handles the chat. C++ has <thread>, which you may want to look into.

A separate thread is easier to implement in this case because you've a separate connection, and separate sockets therefore, that would otherwise need to be looked after for concurrent access.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182753

There are two good ways to do this:

  1. Use threads. Have a thread to handle your TCP sockets and a thread to handle your UDP sockets.

  2. Use a reactor. Both the UDP code and the TCP code register their sockets with the reactor. The reactor blocks on all the sockets (typically using poll) and calls into the appropriate code when activity occurs on that socket.

There are lots of libraries out there for both of these options (such as libevent and boost.asio) that you can use if you don't want to reinvent the wheel.

Upvotes: 5

Related Questions