py server help

Download Raw Clone


  1. import socket
  2. import threading
  3. class ThreadedServer(object):
  4. def __init__(self, host, port):
  5. self.host = host
  6. self.port = port
  7. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  8. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  9. self.sock.bind((self.host, self.port))
  10. def listen(self):
  11. self.sock.listen(5)
  12. while True:
  13. client, address = self.sock.accept()
  14. client.settimeout(60)
  15. threading.Thread(target=self.listen_to_client, args=(client, address)).start()
  16. print("Connected with " + self.host + ":" + str(self.port))
  17. def listen_to_client(self, client, address):
  18. size = 1024
  19. while True:
  20. try:
  21. data = client.recv(size)
  22. if data:
  23. # Set the response to echo back the received data
  24. response = data
  25. print(response)
  26. client.send(response)
  27. else:
  28. raise error('Client disconnected')
  29. except:
  30. client.close()
  31. return False
  32. if __name__ == "__main__":
  33. while True:
  34. port_num = input("Port? ")
  35. try:
  36. port_num = int(port_num)
  37. break
  38. except ValueError:
  39. pass
  40. ThreadedServer('127.0.0.1', port_num).listen()

Raw paste data: