title: [Python]How to implement a TCP client that can receive data from a multiple-thread server constantly?
body: <p>How to implement a TCP client(called <strong>B</strong>) to receive data from a <strong>multiple-thread server</strong> constantly? That is to say, once the server receives data from any other clients, it will forward the data to client B and client B will receive the data as expected. In short, the client B can keep polling the server. <br>
  I implemented my <strong>multi-thread server</strong> as follows:</p>
  <pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
  import socket
  import threading
  import pickle
  
  
  class ThreadedServer:
      def __init__(self):
          self.thread = threading.Thread
          self.thread.__init__(self)
          self.host = socket.gethostname()
          self.port = 49159
          # 49152-65535
          self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, 1)     # socket.SO_REUSEADDR
          '''
          the SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, 
          without waiting for its natural timeout to expire.
          '''
          self.sock.bind((self.host, self.port))
          self.messageList = []
  
      def listen(self):
          print('[STARTING] Server is starting')
          self.sock.listen(5)
          while True:
              connect, address = self.sock.accept()
              connect.settimeout(60)
              thread_ = self.thread(target=self.listenToClient, args=(connect, address))
              thread_.start()
              thread_.join()
  
      def displayMessageHex(self):
          assert isinstance(self.messageList, list), 'message is not a list'
          assert len(self.messageList) &gt; 0, 'message is empty'
          assert isinstance(self.messageList[0], int), 'message is not a int list'
          msg_hex = []
          for msg in self.messageList:
              msg_hex.append('0x{:04x}'.format(msg).upper().replace('0X', '0x'))
          print(msg_hex)
  
      def listenToClient(self, connect, address):
          # print(inspect.stack()[0][3])
          block_size = 1024
          print('Got connection from ', address)
          msg = connect.recv(block_size)
          # [0x]
          message = pickle.loads(msg)
          # print(str(message) + ' fxxk!!!!!')
          if message == 'Give me wer Packet':
              # print('fxxk!!!')
              if len(self.messageList) &gt; 0:
                  connect.sendall(pickle.dumps(self.messageList))
                  self.messageList.clear()
              else:
                  print('Empty message list.')
                  response_msg = 'Empty message list'
                  response_message = pickle.dumps(response_msg)
                  connect.sendall(response_message)
          else:
              self.messageList.append(message)
              connect.sendall(pickle.dumps('I got it'))
          print('thread bye!')
          connect.close()
  
  
  if __name__ == &quot;__main__&quot;:
      TS = ThreadedServer()
      TS.listen()
  </code></pre>
  <p>And the following code is the <strong>client</strong> that will <strong>send data(message)</strong> to the <strong>server</strong>.</p>
  <pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
  import socket  # Import socket module
  import pickle
  
  # 49152-65535
  s = socket.socket()  # Create a socket object
  host = socket.gethostname()  # Get local machine name
  port = 49156  # Reserve a port for your service.
  
  s.bind((host, port))  # Bind to the port
  
  try:
      s.connect((host, 49159))
      print(&quot;Connected Successfully!&quot;)
  except Exception as e:
      print(&quot;something's wrong with %s:%d. Exception is %s&quot; % (host, 49159, e))
  
  
  print('~~message~~')
  wer_Packet = [0xAAAA, 0xFFFF]
  
  
  wer_Packet_b = pickle.dumps(wer_Packet)
  s.send(wer_Packet_b)
  
  response_message = s.recv(1024)
  response_msg = pickle.loads(response_message)
  print('response message:')
  print(response_msg)
  
  s.close()
  </code></pre>
  <p>The <strong>client B</strong> looks like the following one:</p>
  <pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
  
  import socket
  import pickle
  
  HOST = socket.gethostname()
  PORT = 65439
  
  
  def main():
      # instantiate a socket object
      sock = socket.socket()
      sock.bind((HOST, PORT))
      print('Socket Instantiated.')
  
      # connect the socket
      # connection_successful = False
      # while not connection_successful:
      #     try:
      #         sock.connect((HOST, 49159))
      #         # Note: if execution gets here before the server starts up, this line
      #         # will cause an error, hence the try-except
      #         print('socket connected')
      #         connection_successful = True
      #     except:
      #         pass
  
      global i
      i = 0
      global j
      j = 0
      # message = receiveTextViaSocket(sock)
      # i += 1
      # print(' Oops! -- ' + str(i))
      # print('Received Messages:')
      # if isinstance(message, str):
      #     print(message)
      # else:
      #     for _ in message:
      #         print(_)
  
      while True:
          connection_successful = False
          j += 1
          print('Fxxk Oops! -- ' + str(j))
  
          while not connection_successful:
              try:
                  sock.connect((HOST, 49159))
                  # Note: if execution gets here before the server starts up, this line
                  # will cause an error, hence the try-except
                  print('socket connected')
                  connection_successful = True
              except:
                  pass
          i += 1
          print('Oops! -- ' + str(i))
          # time.sleep(0.1)
          message = receiveTextViaSocket(sock)
  
          print('Received Messages:')
          if isinstance(message, str):
              print(message)
          else:
              for _ in message:
                  print(_)
  
  
  def receiveTextViaSocket(sock):
      required_message = pickle.dumps('Give me wer Packet')
      sock.send(required_message)
      # get the text via the socket
      received_messages = sock.recv(1024)
  
      # if we didn't get anything, log an error and bail
      if not received_messages:
          print('error: encodedMessage was received as None')
          return None
      # end if
  
      # decode the received text message
      message = pickle.loads(received_messages)
      return message
      # end function
  
  
  if __name__ == '__main__':
      main()
  </code></pre>
  <p>The output results of the <strong>server</strong> are as follows:</p>
  <pre><code>[STARTING] Server is starting
  Got connection from  ('127.0.0.1', 49156)
  thread bye!
  Got connection from  ('127.0.0.1', 65439)
  thread bye!
  </code></pre>
  <p>The output results of the client that sends data are as follows:</p>
  <pre><code>Connected Successfully!
  ~~message~~
  response message:
  I got it
  
  Process finished with exit code 0
  </code></pre>
  <p>The output results of the <strong>client B</strong> are as follows:</p>
  <pre><code>Socket Instantiated.
  Fxxk Oops! -- 1
  socket connected
  Oops! -- 1
  Received Messages:
  [43690, 65535]
  Fxxk Oops! -- 2
  </code></pre>
  <p>My problem: Why the <strong>client B</strong> cannot receive data from the <strong>server</strong> constantly but just got stuck after the first accept? <br>
  The diagram of send-forward-receive is as follows: <br>
  <a href="https://i.stack.imgur.com/GvL1d.png" rel="nofollow noreferrer">The diagram of send-forward-receive</a> <br>
  Big thank in advance to any kind and constructive comments and answers.</p>