2017-10-28 163 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)