Skip to content
Prev 61351 / 63421 Next

Question on non-blocking socket

On 2/15/23 16:44, Ben Engbers wrote:
Without knowing more details, this looks ok. If you have a non-blocking 
connection, and the server produces a response based on the client 
request, the client has to take into account that it takes the server 
some time to produce the response. Right, the sockets are full duplex 
and so could be the communication protocol, but in this case it 
apparently isn't, it is request/response.

Without the second line, there would be a race condition between the 
server sending a response and the client receiving it. With the second 
line, the client waits for the server before it starts receiving. In 
theory, one could be waiting for the response actively in a loop 
(polling), but socketSelect() is better. Both ways would resolve the 
race condition. Adding a single fixed-time wait, instead, would not 
remove the race condition, because one can never be sure that the server 
wouldn't take longer (apart from waiting too long most of the time).

In the example you are waiting only for a single byte. But if the 
response may be longer, one needs to take into account in the client 
that not all bytes of the response may be available right away. One 
would keep receiving the data in a loop, as they become available (e.g. 
socketSelect() would tell), keep appending them to a buffer, and keep 
looking for when they are complete.

Tomas