2

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()
1
  • Use the conn socket to send the right message to the right client and also take the tcpServer.listen(4) out of the loop Commented Oct 28, 2017 at 17:57

2 Answers 2

1

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

Comments

0

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.

Comments

Your Answer

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.