DeaD_EyE

corrected version, should work :-D

Feb 25th, 2020
114
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import time
  2. from socket import socket, AF_INET, SOCK_STREAM, timeout as socket_timeout
  3. from threading import Thread
  4.  
  5.  
  6. class Client:
  7.     QUIT = "{quit}"
  8.  
  9.     def __init__(self, name, host="localhost", port=5500, buffer_size=1024, timeout=5):
  10.         self.connected = False
  11.         self.running = False
  12.         self.name = name
  13.         self.addr = (host, port)
  14.         self.buffer_size = buffer_size
  15.         self.socket = socket(AF_INET, SOCK_STREAM)
  16.         self.socket.settimeout(timeout)
  17.         self.socket.connect(self.addr)
  18.         self.connected = True
  19.         self.running = True
  20.         self.send_message(name)
  21.         receive_thread = Thread(target=self.receive)
  22.         receive_thread.start()
  23.  
  24.     def send_message(self, msg):
  25.         if not self.running:
  26.             raise ConnectionError("Client is not running or connected")
  27.         if msg == self.QUIT:
  28.             self.running = False
  29.         sock = self.socket
  30.         try:
  31.             sock.sendall(msg.encode())
  32.         except Exception as e:
  33.             print("Message send failure in client.send_message()")
  34.             print("Exception: ", e)
  35.             self.running = False
  36.             self.connected = False
  37.  
  38.     def receive(self):
  39.         sock = self.socket
  40.         incoming_message = None
  41.         while self.running:
  42.             try:
  43.                 incoming_message = sock.recv(self.buffer_size).decode().rstrip()
  44.                 # the rsplit removes whitespace and newline form the
  45.                 # right side of the string, makes testing with
  46.                 # netcat easier
  47.             except socket_timeout:
  48.                 continue
  49.             except Exception as e:
  50.                 print(f"Exception {e} in receive method\nstopping loop")
  51.                 break
  52.             if not incoming_message or incoming_message == self.QUIT:
  53.                 print("Connections was closed or {quit} was received")
  54.                 self.running = False
  55.                 break
  56.             print(incoming_message)
  57.  
  58.     def disconnect(self):
  59.         if self.connected:
  60.             self.send_message(self.QUIT)
  61.         else:
  62.             self.running = False
  63.  
  64.  
  65. if __name__ == "__main__":
  66.     try:
  67.         client = Client("Testclient\n")
  68.     except Exception as e:
  69.         print(e)
  70.     else:
  71.         for n in range(10):
  72.             client.send_message(f"Hello World {n}\n")
  73.             time.sleep(1)
  74.         client.disconnect()
RAW Paste Data