what is TCP blocking and non-blocking mode in socket module in python3

Balbir Singh
Balbir Singh used Ask the Experts™
what is TCP blocking and non-blocking mode in socket module in python

I am trying to understand what it means and under which situation we should use it. I am not able to find a proper example to understand it. I really appreciate if any example can be shared to understand it better.

Thank you!
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fractional CTO
Distinguished Expert 2018
https://jameshfisher.com/2017/04/05/set_socket_nonblocking/ demonstration code of non-blocking, which is exactly what it sounds like.

A non-blocking socket, never blocks, which is the basis of event looping.

For example, the high speed Apache Event MPM, so in this case, rather than one connection/process you have one process for all connections, which dramatically speeds up request processing... which is what makes the entire HTTP/2 protocol process all requests in parallel.

If you're really interested in this topic, take a look at the entire HTTP/2 protocol.

You can also take a look at the many PERL async libraries.

Tip: Python, PERL, C, C++, Ruby, whatever... Sockets are Sockets... all the same in any language...
fread fwrite and other socket related calls will make thd process wait until the operation either completes or aborts for reasons such as receiving a signal or timeouting.

on non blocking sockets, said calls will return immediately and report what they were able to do. Some implementations will honor timeouts so set them to zero for true non blocking mode

Asynchronous programming can be achieved with either mode but non blocking is both more intuitive and prevents unintentional blocking calls.
nociSoftware Engineer
Distinguished Expert 2018
In addition to skullnobrains remark..
There are several methods (poll(), epoll(), kqueue(), select() )  to wayt for any IO readyness on a list of FileHandles (sockets).

So you can efficiently wait until on of the sockets is ready to do the next step. ( more reading, writing, etc. etc.)
Not all systems support all waiting calls the same way. Those should also be available in scripting languages if you are able to set a Filehandle (Socket) to non-blocking mode.
See also:
agreed. just to clear things up, select, kevent and othet related calls also work on blocking sockets. I usually run my first benchmarks in blocking mode which helps to check for mistakes in async programs.

The non blocking sockets allows to do A poor man's async programming without using such system calls, by manually polling file descriptors.

So basically blocking or non blocking is not really about asynchronous programming.

Event driven, mpm, http2 are completely off topic.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial