0

When I do socket programming with python,
I notice that some operations didn't stop by interrupt. Ex: accept() or recv()
So I solve this problem using small timeout, that every 1 second, program stop the operation and recall that. For example,

socket.settimeout(1)    
while True:
    try:
        socket.recv()
    except timeout:
        # back to socket.recv()
        continue
    except KeyboardInterrupt:
        break

Is there some potential problem like losing some messages during timeout exception or heavy load to OS, etc?

And, do you have any better idea to stop socket not using the timeout? Please tell me then I appreciate your answer.

There is one more thing need to consider. I test this program in Windows, and KeyboardInterrupt actually raise after recv() is done even if I press ctrl+C. But in MacOS or Linux, KeyboardInterrupt raise just after pressing ctrl+C. Is there difference between Windows and Linux/Unix?

1 Answer 1

0

With sockets, the risk of losing data depends on the socket type.

With SOCK_DGRAM sockets, there is no promise that the protocol is reliable. This means that in general you should expect that some messages will be lost no matter how you program recv() calls.

With SOCK_STREAM, there is a promise that the incoming stream of data will be reliable and in the same order it was sent.

If you call socket.settimeout(0) or socket.setblocking(False), then recv() checks the socket's receive buffer for incoming data, and if there is none, it fails with an error that depends on the operating system. This could be used to poll periodically for data while also doing other things. However, it can also introduce operating system-specific behavior to your program.

Another common technique is to create a thread whose sole purpose is to send and receive a socket that is set to blocking mode [socket.setblocking(True)]. In this case the thread can call recv() and wait as long as necessary until data actually comes in. This setup lets you program a protocol as a conversation between send() and recv() calls.

For applications that handle messages from several sockets at a time, select() can be used to figure out which sockets in a set have pending data to recv(). One caution is that select() can be inefficient in situations that demand high performance.

2
  • A zero timeout value means infinity, not zero. It is not a mechanism for polling the socket.
    – user207421
    Apr 5, 2018 at 3:11
  • 1
    @EJP According to documentation for socket.settimeout(), zero puts the socket in non-blocking mode, while None, puts it in blocking mode (infinite timeout).
    – Jack C.
    Apr 6, 2018 at 2:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.