多线程套接字TCP服务器

时间:2017-10-28 17:21:01

标签: python multithreading sockets tcp tcpserver

我正在尝试实现一个简单的多线程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()

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

我认为listen调用应该不在循环中。它使您的服务器能够接受连接,只需要调用一次。

相关问题