title: Python Socket Message Exchange
body: <p>I have to edit this code i have in python of a chatServer so that you can send private messages to a receiver and if the recevier isnt logged in it outputs an error to the sender. Also any message sent by the server to the client must be provided with the name of the original sender.</p>
  
  <h2>chatClient.py</h2>
  
  <pre><code>import socket
  import struct
  import sys
  import threading
  from datetime import datetime
  
  PORT = 8888
  HEADER_LENGTH = 2
  
  
  def receive_fixed_length_msg(sock, msglen):
      message = b''
      while len(message) &lt; msglen:
          chunk = sock.recv(msglen - len(message))
          if chunk == b'':
              raise RuntimeError("socket connection broken")
          message = message + chunk
      return message
  
  
  def receive_message(sock):
      header = receive_fixed_length_msg(sock, HEADER_LENGTH)
      message_length = struct.unpack("!H", header)[0] 
  
      message = None
      if message_length &gt; 0: 
          message = receive_fixed_length_msg(sock, message_length) 
          message = message.decode("utf-8")
  
      return message
  
  
  def send_message(sock, message):
      encoded_message = message.encode("utf-8") 
      header = struct.pack("!H", len(encoded_message))
  
      message = header + encoded_message 
      sock.sendall(message);
  
  def message_receiver():
      while True:
          msg_received = receive_message(sock)
          if len(msg_received) &gt; 0:  # ce obstaja sporocilo
              current_time = datetime.now().strftime('%H:%M:%S')
              print("[RKchat][" + current_time + "] " + name + ": " + msg_received)
  
  print("[system] connecting to chat server ...")
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect(("localhost", PORT))
  print("[system] connected!")
  
  thread = threading.Thread(target=message_receiver)
  thread.daemon = True
  thread.start()
  
  name = input("Vpiši ime: ")
  
  while True:
      try:
          msg_send = input("")
          send_message(sock, msg_send)
      except KeyboardInterrupt:
          sys.exit()
  </code></pre>
  
  <h2>chatServer.py</h2>
  
  <pre><code>import signal
  
  signal.signal(signal.SIGINT, signal.SIG_DFL)
  import socket
  import struct
  import threading
  
  PORT = 8888
  HEADER_LENGTH = 2
  
  
  def receive_fixed_length_msg(sock, msglen):
      message = b''
      while len(message) &lt; msglen:
          chunk = sock.recv(msglen - len(message)) 
          if chunk == b'':
              raise RuntimeError("socket connection broken")
          message = message + chunk  # pripni prebrane bajte sporocilu
  
      return message
  
  
  def receive_message(sock):
      header = receive_fixed_length_msg(sock, HEADER_LENGTH)
      message_length = struct.unpack("!H", header)[0]
  
      message = None
      if message_length &gt; 0:
          message = receive_fixed_length_msg(sock, message_length)
          message = message.decode("utf-8")
  
      return message
  
  
  def send_message(sock, message):
      encoded_message = message.encode("utf-8")
  
      header = struct.pack("!H", len(encoded_message))
  
      message = header + encoded_message
      sock.sendall(message);
  
  def client_thread(client_sock, client_addr):
      global clients
  
      print("[system] connected with " + client_addr[0] + ":" + str(client_addr[1]))
      print("[system] we now have " + str(len(clients)) + " clients")
  
      try:
          while True:
              msg_received = receive_message(client_sock)
  
              if not msg_received: 
                  break
  
              print("[RKchat] [" + client_addr[0] + ":" + str(client_addr[1]) + "] : " + msg_received)
  
              for client in clients:
                  send_message(client, msg_received.upper())
      except:
          pass
  
      with clients_lock:
          clients.remove(client_sock)
      print("[system] we now have " + str(len(clients)) + " clients")
      client_sock.close()
  
  server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  server_socket.bind(("localhost", PORT))
  server_socket.listen(1)
  
  print("[system] listening ...")
  clients = set()
  clients_lock = threading.Lock()
  while True:
      try:
          client_sock, client_addr = server_socket.accept()
          with clients_lock:
              clients.add(client_sock)
  
          thread = threading.Thread(target=client_thread, args=(client_sock, client_addr));
          thread.daemon = True
          thread.start()
  
      except KeyboardInterrupt:
          break
  
  print("[system] closing server socket ...")
  server_socket.close()
  </code></pre>