socket.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import socket
  2. import threading
  3. from .worker.connector import Connector
  4. from .worker.cryptor import Cryptor
  5. from .worker.bearer import Bearer
  6. import config as cfg
  7. import json
  8. class Socket():
  9. def __init__(self, socketPort):
  10. self.socketPort = socketPort
  11. t = threading.Thread(target=self.connection)
  12. t.start()
  13. print("socket is created and Listener is created",socketPort)
  14. def connection(self):
  15. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  16. s.bind(("localhost", self.socketPort))
  17. s.listen()
  18. self.socket = s
  19. while True:
  20. conn, addr = self.socket.accept()
  21. print(conn, addr)
  22. u = threading.Thread(target=Connection,args=(conn, addr,self.socketPort+1)) # TODO socketprot dynamic
  23. u.start()
  24. class Connection(threading.Thread):
  25. def __init__(self,connection,address,oracleSocketPort):
  26. super(Connection,self).__init__(None, None,
  27. None, None)
  28. self.conn = connection
  29. self.addr = address
  30. self.history = []
  31. self.type = None
  32. self.oracleSocketPort = oracleSocketPort
  33. t = threading.Thread(target=self.receive)
  34. t.start()
  35. # self.send("Connection")
  36. def toSEND(self,oracle, data):
  37. j = json.dumps(x)
  38. l = LenFunc - len(str(len(j)))
  39. oracle.send("0000"[0:l]+str(len(j))+j)
  40. def send(self,Message):
  41. Message=bytes(Message,'utf-8')
  42. self.conn.sendall(Message)
  43. # self.history.append(("send",Message))
  44. def receive(self):
  45. while True:
  46. len = self.conn.recv(cfg.LenFunc)
  47. if not len:
  48. break
  49. data = self.conn.recv(int(len))
  50. if not self.type:
  51. d = json.loads(data)
  52. if d["type"] == "user":
  53. if d["oracle"] == 0:
  54. self.type = Connector(self)
  55. elif d["oracle"] == 1:
  56. self.type = Cryptor(self)
  57. elif d["oracle"] == 2:
  58. self.type = Bearer(self)
  59. else:
  60. print("data",data)
  61. self.type.parser(data.decode("utf-8"),self.conn)
  62. # self.history.append(("receive",data))