Reputation: 391
I write a TCP server using Python. I want the server only accept on client connection.
I use the listen
function
listen(1)
but the server still can accepts more than one connection.
Upvotes: 1
Views: 4270
Reputation: 1079
If you want only one connection, pleae don't use loop for socket.accept()
in- connections.
#!/usr/bin/python
import time
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_addr = ('127.0.0.1', 8080)
server.bind(server_addr)
server.listen(1)
print("listening on {}".format(server_addr))
client, client_addr = server.accept()
for i in range(10):
client.send("num: {}\n".format(i))
time.sleep(1)
raw_input('')
Upvotes: 1
Reputation:
From the documentation:
If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections.
So if you use listen(1)
you allow one unaccepted connection. If you want to allow no unaccepted connections, you must use listen(0)
.
Upvotes: 1