0

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
asked Sep 29, 2021 at 16:06
2
  • How did you determine that the server doesn't accept more connections? Commented 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. Commented Oct 7, 2021 at 8:54

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.