I'm trying to limit a Python server to only accept a connection from one client, but I'm noticing that the Python server always accepts one too many connections. Here is the server code:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(0)
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
while True:
time.sleep(1000)
clientsocket.send(bytes("Welcome to server 1!", "utf-8"))
I would expect this to only allow one client connection at a time, since there is not allowed to be any in the queue (s.listen(0)
). However, I'm finding that this code allows me to connect two clients before getting an error. Here are my clients connecting:
>>> import socket
>>> socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((socket.gethostname(), 1234))
>>> socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((socket.gethostname(), 1234))
>>> socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((socket.gethostname(), 1234))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
The first client is accepted, which is expected. The second client successfully connects, which I would not expect since the server already has a connection and 0 connections are allowed in the queue. We do not fail until the third client tries to connect and is denied.
If we up the listen()
argument to 1, we are allowed 3 connections (1 current, 2 in the queue). If we up it to 2, we are allowed 4 connections (1 current, 3 in the queue). This pattern continues.
How can I specify that my server should allow allow 1 connection and not hold any in the queue?