socketClient.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import socket
  2. import threading
  3. import config as cfg
  4. import json
  5. LenFunc = cfg.LenFunc
  6. class Socket(threading.Thread):
  7. def __init__(self, HOST,PORT,data):
  8. super(Socket,self).__init__(None,None,None,None)
  9. self.port = PORT
  10. self.Host = HOST
  11. self.history = []
  12. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  13. self.socket.connect((HOST, PORT))
  14. t = threading.Thread(target=self.receive)
  15. t.start()
  16. print("socket is created and Listener is created\n")
  17. self.toSEND(data)
  18. def send(self,Message):
  19. Message=bytes(Message,'utf-8')
  20. self.socket.sendall(Message)
  21. # self.history.append(("send",Message))
  22. print("Send",Message)
  23. def receive(self):
  24. while True:
  25. len = self.socket.recv(LenFunc)
  26. if not len:
  27. break
  28. data = self.socket.recv(int(len))
  29. print("data",data)
  30. # self.history.append(("receive",data))
  31. def toJSON(self, data):
  32. return json.loads(data)
  33. def toSTRING(self, data):
  34. return json.dumps(data)
  35. def toSEND(self, x):
  36. j = json.dumps(x)
  37. l = LenFunc - len(str(len(j)))
  38. self.send("0000"[0:l]+str(len(j))+j)
  39. def parser(self,data):
  40. print("parser not yet implemented. ",data)