oracle.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/python
  2. import socket
  3. import _thread
  4. import time
  5. import socket
  6. import os
  7. import random
  8. from padra import padra
  9. LenFunc = 4
  10. padra = padra(LenFunc)
  11. HOST = '127.0.0.1' # Standard loopback interface address (localhost)
  12. socketPort = int(random.random()*5000+1024)
  13. def broadcast():
  14. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  15. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  16. sock.bind(("", 6666))
  17. while True:
  18. msg, addr = sock.recvfrom(1024)
  19. sock.sendto(bytes(str(socketPort),'utf-8'),addr)
  20. connectedUser = []
  21. def listen():
  22. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  23. s.bind((HOST, socketPort))
  24. s.listen()
  25. while True:
  26. conn, addr = s.accept()
  27. u = _thread.start_new_thread( user, (conn, addr))
  28. connectedUser.append((addr,u))
  29. class user():
  30. def __init__(self,connection,address):
  31. self.conn = connection
  32. self.addr = address
  33. self.history = []
  34. _thread.start_new_thread( self.receive, ())
  35. self.send("Connected")
  36. def send(self,Message):
  37. Message=bytes(Message,'utf-8')
  38. self.conn.sendall(Message)
  39. self.history.append(("send",Message))
  40. def receive(self):
  41. while True:
  42. len = self.conn.recv(LenFunc)
  43. if not len:
  44. break
  45. data = self.conn.recv(int(len))
  46. padra.parse(data.decode("utf-8"))
  47. self.history.append(("receive",data))
  48. try:
  49. _thread.start_new_thread( broadcast, ())
  50. _thread.start_new_thread( listen, ())
  51. except:
  52. print ("Error: unable to start thread")
  53. while 1:
  54. pass