Problem: My server application only accepts one connection at a time. I'd like to know why serverSocket.listen() doesn't listen and serverSocket.accept() doesn't accept all connections.
import socket
SERVER_ADDRESSES = ['0.0.0.0']
SERVER_PORT = 8091
CONNECTED_CLIENTS = {}
def processClientConnection(clientSocket, clientAddress):
while True:
try:
print("Listening for messages...")
message = clientSocket.recv(1024)
message = message.decode("UTF-8")
for client in CONNECTED_CLIENTS.keys():
print(f"{CONNECTED_CLIENTS[client]} vs {clientAddress}")
print(CONNECTED_CLIENTS[client] == clientAddress)
if CONNECTED_CLIENTS[client] != clientAddress:
print(f"Sending message to {CONNECTED_CLIENTS[client]}")
client.send(b"%s: %s" % (CONNECTED_CLIENTS[client][0], message))
except ConnectionResetError:
print(f"{CONNECTED_CLIENTS[clientSocket][0]} disconnected!")
for client in CONNECTED_CLIENTS.keys():
if clientSocket != client:
client.send(b"%s disconnected!" % CONNECTED_CLIENTS[clientSocket][0])
del(CONNECTED_CLIENTS[clientSocket])
def startServer(serverAddress):
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket Host Name: {serverAddress}:{SERVER_PORT}")
serverSocket.bind((serverAddress, 8091))
# become a server socket
while True:
print("Listening for connections")
serverSocket.listen()
(clientSocket, address) = serverSocket.accept()
if (clientSocket, address) in CONNECTED_CLIENTS:
print("Can't connect multiple of same client")
break
CONNECTED_CLIENTS[clientSocket] = address
print(f"{CONNECTED_CLIENTS[clientSocket][0]} connected!")
ct = threading.Thread(target=processClientConnection, args=([clientSocket, address]))
ct.run()
def runServer():
for serverAddress in SERVER_ADDRESSES:
serverThread = threading.Thread(target=startServer, args=([serverAddress]))
serverThread.start()
if __name__ == '__main__':
print('Server Started')
runServer()
import socket
SERVER_ADDRESS = '127.0.0.1'
SERVER_PORT = 8091
def receiveMessage(sock):
while True:
try:
message = sock.recv(1024).decode("UTF-8")
if len(message):
print(message)
except ConnectionResetError:
print("Server disconnected you")
sock.close()
exit(0)
except ConnectionAbortedError:
print("Server disconnected you")
sock.close()
exit(0)
def sendMessage(sock):
while True:
try:
message = input()
sock.send(bytes(message, "UTF-8"))
except ConnectionResetError:
print("Server disconnected you")
sock.close()
exit(0)
except ConnectionAbortedError:
print("Server disconnected you")
sock.close()
exit(0)
except EOFError:
print("Client closed")
sock.close()
exit(0)
def runClient():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((SERVER_ADDRESS, SERVER_PORT))
except TimeoutError:
print("Server down")
s.close()
exit(0)
except ConnectionRefusedError:
print("Server down")
s.close()
exit(0)
print("Connected to server. Type your message.\n")
messagingThread = threading.Thread(target=sendMessage, args=([s]))
messagingThread.start()
receivingThread = threading.Thread(target=receiveMessage, args=([s]))
receivingThread.start()
if __name__ == '__main__':
print("Client started")
runClient()
Alex Howansky
54.1k8 gold badges85 silver badges102 bronze badges
-
How did you determine that the server doesn't accept more connections?mkrieger1– mkrieger12021年09月29日 16:12:35 +00:00Commented Sep 29, 2021 at 16:12
-
Please trim your code to make it easier to find your problem. Follow these guidelines to create a minimal reproducible example.Community– Community Bot2021年10月07日 08:54:27 +00:00Commented Oct 7, 2021 at 8:54
1 Answer 1
while True:
print("Listening for connections")
serverSocket.listen()
(clientSocket, address) = serverSocket.accept()
...
ct = threading.Thread(target=processClientConnection, args=([clientSocket, address]))
ct.run()
This is wrong in multiple ways:
- A server socket should be created once, should be bound once to the address and should call listen once in order to setup the listen queue. After that accept should be called again and again to get the newly established connections. You instead create it once, bind it once but then call listen again and again.
- You are attempting to create a new thread for each new connection in order to handle the new client connection in parallel to the other activity. But since you use ct.run() instead of ct.start() the thread function will be called directly within the current thread and not in parallel to the existing one. This means new connections will only be accepted once the code is done with the current one.
answered Sep 29, 2021 at 17:27
Steffen Ullrich
125k11 gold badges157 silver badges194 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py