2017-10-28 182 views
2

我想实现一个简单的多线程TCP服务器。当只有一个连接的客户端时,它运行良好,但当同时连接两个客户端时,第一个客户端的线程有时会收到必须由第二个客户端接收的消息。如何处理他的问题?Python。多线程套接字TCP服务器

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() 
+0

使用'conn'套接字将正确的消息发送到正确的客户端,并且还将'tcpServer.listen(4)'带出循环 –

回答

0

我认为listen调用应该没有循环。它使你的服务器能够接受连接并且只需要被调用一次。

1

我发现了这个错误。这里data = conn.recv(1024)conn是全局变量,所以它是最后连接的客户端的套接字,所有的线程都试图从它接收数据。以下代码效果很好:

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)