title: Multithreaded socket TCP server
body: <p>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?</p>
  
  <pre><code>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()
  </code></pre>