Reputation: 31
I am trying to implement a simple multithreaded TCP server. It works well when there is only one connected client, but when there are two clients connected at the same time, the thread for the 1st client sometimes receives a message that has to be received by the second one. How to deal with his problem?
class ClientThread(Thread):
def __init__(self, ip, port):
Thread.__init__(self)
self.ip = ip
self.port = port
#...
def run(self):
while True:
try:
data = conn.recv(1024)
#...
except ConnectionResetError:
break
TCP_IP = '0.0.0.0'
TCP_PORT = 1234
BUFFER_SIZE = 1024
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpServer.listen(4)
(conn, (ip, port)) = tcpServer.accept()
newthread = ClientThread(ip, port)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
Upvotes: 2
Views: 1505
Reputation: 31
I've found the bug. Here data = conn.recv(1024)
conn
is the global variable, so it is the socket for last connected client, and all the threads are trying to receive data from it. The following code works well:
class ClientThread(Thread):
def __init__(self, ip, port, conn):
Thread.__init__(self)
self.ip = ip
self.port = port
self.conn = conn
#...
def run(self):
while True:
try:
data = self.conn.recv(1024)
#...
except ConnectionResetError:
break
........
newthread = ClientThread(ip, port, conn)
Upvotes: 1
Reputation: 43096
I think that the listen
call should be out of the loop. It makes your server able to accept connections and need to be called only once.
Upvotes: 0