2

I'm new to Python and interested in socket programming these days. From the youtube videos, I'm building a simple server but I didn't get listen() method very well. I know "it listens" incoming connections but I didn't get the the idea of "maximum queued connections" in the document. Could you explain this concept in layman's terms so that I can understand better?

phihag
  • 278,196
  • 72
  • 453
  • 469
Süleyman Yaman
  • 241
  • 2
  • 3
  • 10

1 Answers1

7

socket.listen in Python calls the underlying listen syscall:

listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(2).

A passive socket is the one you'd informally call the server.

The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.

In other words, when you call sock.listen(5) and 6 connection requests come in before you call accept, one of them is getting dropped. In practice, the value is only a hint to the OS.

Unless your application or its usage scenario is extraordinary, pass in any value - 5 is often quoted - and be done. Just make sure that you don't have too much overhead between accept calls, and the queue of pending connections will never be full and only rarely used in the first place.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • Thanks for your reply. Can we liken this to the process in which many people try to access a web site and some of them can't access? For example, this always happens when all the people in my campus try to access the web site in order to register their courses :) – Süleyman Yaman Jan 14 '18 at 02:27
  • Yes, overload is the typical scenario when the receive queue comes into play. However, a large backlog number is not helpful in that case: If a server is under too much load to handle, extending the receive queue will only mean more load in managing the waiting connections. In an overload situation, you really want to terminate new incoming connections as quickly as possible, so that at least some queries have a chance of completion. – phihag Jan 14 '18 at 08:58