Search code examples
pythonsocketsserver-side

Arbitrarily large number of sockets - Python


I recently started searching for socket programming, and decided to use python for testing. I have the following question: As I read, you can only listen for a limited number of connections in a server-side socket, thus you can only have such a number of connections operating at a time. Is there a way to be able to hold as many sockets open as the system can tolerate? That is e.g. in the case of a chat server (you would not want to only have 5 active users at a time, for example).

What's the solution to that? Should one create more sockets to achieve that goal? But then, would the number of ports available to the system be the next limitation?


Solution

  • If you are asking about function 'listen':

    'backlog' argument is the maximum length to which the queue of pending connections for socket 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.

    This does not set any limit on number of socket connections. Only the ones which were not 'accept'-ed yet (e.g. have not become 'connection').

    When client tries to connect the backlog grows by 1.

    When you call 'accept' the backlog decreases by 1.

    So if you will call 'accept' periodically you will open a number of connections.