boilerplate

server.py 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import socket, sys, datetime, threading, json
  2. class Server:
  3. def __init__(self):
  4. self.version = 1.0
  5. print("Server version: {}".format(self.version))
  6. self.motd = "cubey"
  7. self.color = 0xe973ea
  8. self.users = []
  9. self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  10. print("Created socket object")
  11. self.ip = "0.0.0.0"
  12. self.port = 1337
  13. self.address = (self.ip, self.port)
  14. self.sock.bind(self.address)
  15. print("Server started up on {}".format(self.address))
  16. def send(self, data, client):
  17. data = json.dumps(data).encode()
  18. self.sock.sendto(data, client)
  19. def send_all(self, data):
  20. for user in self.users:
  21. self.send(data, user)
  22. def connection(self, address, connecting_client_name):
  23. print("New connection from {}".format(address))
  24. a = {"header":"connection",
  25. "motd":self.motd,
  26. "color":self.color,
  27. "client name":connecting_client_name}
  28. print(">> " + connecting_client_name + " <<")
  29. self.users.append(address)
  30. self.send_all(a)
  31. def run(self):
  32. while True:
  33. try:
  34. data, addr = self.sock.recvfrom(65507)
  35. a = json.loads(data)
  36. header = a["header"]
  37. client_name = a["client name"]
  38. if header == "connection":
  39. self.connection(addr, client_name)
  40. elif header == "message":
  41. message = a["message"]
  42. print(client_name + " >> " + message)
  43. response = {"header":"response",
  44. "message":message,
  45. "color":0xffffff,
  46. "client name":client_name}
  47. if addr not in self.users:
  48. self.users.append(addr)
  49. self.send_all(response)
  50. except OSError:
  51. return
  52. class Commands:
  53. def __init__(self):
  54. self.commands={"test":self.test,
  55. "stop":self.stop}
  56. self.running = True
  57. def test(self):
  58. print("this is a test command")
  59. def stop(self):
  60. print("Stopping server...")
  61. server.sock.close()
  62. server_thread.join()
  63. self.running = False
  64. def run(self):
  65. while self.running:
  66. command = input()
  67. if command in self.commands:
  68. self.commands[command]()
  69. else:
  70. print("Unknown command")
  71. server = Server()
  72. commands = Commands()
  73. server_thread = threading.Thread(target = server.run)
  74. commands_thread = threading.Thread(target = commands.run)
  75. server_thread.start()
  76. commands_thread.start()