python-3.x – Python sockets: backlog parameter of socket.listen () method

Question:

Hello. Wrote a simple client / server application using sockets. The client sends a string to the server, the server converts that string to uppercase and sends it to the client, and the client just prints this string.

#Сервер
import socket
from threading import Thread

def handler(client_socket, cli_address):
    print(client_address, 'was connected')
    while 1:
        recieve_message = client_socket.recv(1024)
        client_socket.send(recieve_message.upper())

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 5000))
print('server starts')
server_socket.listen(1)
while 1:
    client_socket, client_address = server_socket.accept()
    Thread(target=handler, args=(client_socket, client_address)).start()
#-----------------------------------------
#Клиент
import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 5000))
while 1:
    message = input()
    client_socket.send(message.encode())
    recieve_message = client_socket.recv(1024)
    print(recieve_message.decode())

The question is calling the listen method. It takes the maximum number of connections as a parameter. In this case, it equals 1. But having started the server and five clients, they all work well, why?

Answer:

You do not quite correctly understand this parameter in listen. How the server socket works:

  • the client connects to the server.
  • it is put into the queue (and this parameter for listen determines the size of the queue)
  • if there is no more space in the queue, the client is denied connection.
  • separately, the server itself calls accept on the socket. By doing this, it takes one client off the queue of sockets waiting for a connection.

Now the legitimate question is, how much should the queue size be set? It should be such that the code has time to accept all clients. That is, if you test and connect with one client and the next connection will be only after processing the previous one, then even a size of 1 will be sufficient. If you have a heavily loaded server and clients are thrown there in hundreds, and there may be gaps in the client accept'y in the code, then you need to set more, I saw both 100 and 150. But if clients are knocking down at such a speed that the code does not have time to rake them out, then no queue size will help.

Scroll to Top