Game Development Reference
In-Depth Information
Non-blocking sockets
By default, every socket (it doesn't matter if it's a TcpListener , TcpSocket , or Ud-
pSocket ) is a blocking socket. When a socket is blocking, each of its methods wait until
the operation completes before it returns. For some methods, such as TcpSock-
et::receive() or TcpListener::accept() however, it can take an indefinite
amount of time for something to happen. If the other side is not sending any data or if it's
not trying to connect at all, the server side will get blocked until one of those actions hap-
pen. To solve that problem each socket can be set to a non-blocking state.
All three sockets inherit from the sf::Socket class, which implements the blocking or
non-locking state system. When a socket is in the non-blocking state, its methods return
immediately, if there is nothing happening at the moment or if the data transfer is not ready.
For example calling TcpListener::accept() returns Socket::NotReady if
there is no socket currently waiting to be connected. If the socket is in blocking mode, then
that method waits until there is a client available. The same behavior goes for TcpSock-
et::receive() and UdpSocket::receive() .
This functionality is useful when we are dealing with real time games or applications,
where we expect clients to come and go as well as send us data whenever they want. For
that we need to continue running our main loop and only check once a frame if there is
something waiting for us. If so, we can handle it appropriately or, alternatively, just contin-
ue with our loop and check again next time.
The method that enables the blocking/non-blocking mode is Sock-
et::setBlocking() , which requires a boolean parameter. This is an example of
how to handle UdpSocket , which checks for new data with every frame:
Search WWH ::

Custom Search