title: how to handle variable length message and close the socket automatically?
body: <p>I have the following case:</p>
  
  <p><strong>SERVER</strong></p>
  
  <pre><code>sock = socket.socket()
  sock.bind((hostaddr, port))
  sock.listen(backlog)
  print(f'Server listenning on {hostaddr}:{port}')
  
  while True:
      client_sock, client_address = self.sock.accept()
      print(f'Incoming connection from {client_address[0]}:{client_address[1]}')
  
      while True:
          data = client_socket.recv(buffer_size)
          if not data:
             break
  
          print(f'Received "{data.decode()}" from {client_address[0]}:{client_address[1]}')    
  
          reply = f'Server: I got the message "{data.decode()}"'.encode()
          client_socket.sendall(reply)
  
      client_socket.close()
  </code></pre>
  
  <p><strong>CLIENT</strong></p>
  
  <pre><code>sock = socket.socket()
  sock.connect(server_address)
  sock.sendall('Lorem Ipsum'.encode())
  
  while True:
      data = sock.recv(buffer_size)
      if not data:
          break
      print(data.decode())
  
  sock.close()
  </code></pre>
  
  <hr>
  
  <p>I first start the server, then I start the client, and I get the following logs:</p>
  
  <p><strong>SERVER</strong></p>
  
  <pre><code>Server listening on 172.16.0.110:8081
  Incoming connection from 172.16.0.110:62388
  Received "Lorem Ipsum" from 172.16.0.110:62388
  </code></pre>
  
  <p><strong>CLIENT</strong></p>
  
  <pre><code>Server reply: I got the message "Lorem Ipsum"
  </code></pre>
  
  <p>I wanted to get the server reply and then the client should finish, but both server and client enter an infinite loop and keep running forever. Why and how to fix that? I'm using Python 3.6.0 on Windows 10 x64 in an IPv4 network.</p>