broadcast.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import socket
  2. import threading
  3. from Utils import *
  4. import config as cfg
  5. LenFunc = cfg.LenFunc
  6. class Broadcast:
  7. def __init__(self, parser, socket, child):
  8. """ ,broadcast """ # TODO Broadcast
  9. self.socket = socket
  10. self.parser = parser
  11. self.child = child
  12. t1 = threading.Thread(target=self.listen)
  13. t1.start()
  14. gBackPrint("Broadcast ", "created")
  15. def listen(self):
  16. while True:
  17. data, addr = self.socket.recvfrom(1024)
  18. d = self.parser.toJSON(data.decode("utf-8")[LenFunc:])
  19. vPrint("receive", d, " \n\tfrom", addr, "\n\033[0m")
  20. self.parser.parser(d, addr, self.child)
  21. def send(self, message, addr):
  22. self.socket.sendto(bytes(message, "utf-8"), addr)
  23. bPrint("sended to", (addr, message))
  24. class BroadcastServer(Broadcast):
  25. def __init__(self, broadcastPort, parser, id):
  26. """ ,broadcast """ # TODO Broadcast
  27. self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  28. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  29. self.socket.bind(("", broadcastPort)) # TODO Broadcast
  30. self.id = id
  31. super().__init__(parser, self.socket, self)
  32. class BroadcastClient(Broadcast):
  33. def __init__(self, broadcast, broadcastPort, parser, id):
  34. self.addr = (broadcast, broadcastPort)
  35. self.onlineOracles = []
  36. self.id = id
  37. self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  38. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  39. super().__init__(parser, self.socket, self)