network_api.py 951 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import json
  2. import socket
  3. class NetworkAPI(object):
  4. def __init__(self, addr=None, timeout=None):
  5. self.addr = tuple(addr)
  6. self.ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  7. if addr:
  8. self.bind(tuple(addr))
  9. if timeout:
  10. self.ss.settimeout(timeout)
  11. def bind(self, addr):
  12. self.addr = tuple(addr)
  13. self.ss.bind(addr)
  14. def set_timeout(self, timeout):
  15. self.ss.settimeout(timeout)
  16. def send(self, data, addr):
  17. data = json.dumps(data).encode("utf-8")
  18. self.ss.sendto(data, tuple(addr))
  19. def receive(self, addr=None, timeout=None):
  20. if addr:
  21. self.bind(addr)
  22. if not self.addr:
  23. raise "please bind to an address"
  24. if timeout:
  25. self.set_timeout(timeout)
  26. data, addr = self.ss.recvfrom(65535)
  27. return json.loads(data), addr
  28. def close(self):
  29. self.ss.close()