We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I avoid blocking in the connect() method of a socket?

The select module is commonly used to help with non-blocking I/O on sockets. This module lets you check if one or more sockets are ready for reading or writing, without having to block for an unknown period of time.

To prevent the TCP connect from blocking, you can set the socket to non-blocking mode. Then when you call the connect method, you will either connect immediately (unlikely) or get an exception that contains the error number in its errno attribute. The value errno.EINPROGRESS indicates that the connection is in progress, but hasn’t finished yet. Different OSes will return different values, so you’re going to have to check what’s returned on your system.

You can use the connect_ex method to avoid creating an exception. It will just return the errno value. To poll, you can call connect_ex again later — 0 or errno.EISCONN indicate that you’re connected — or you can pass this socket to select to check if it’s writable.

CATEGORY: library