Python-ELMO is a Python library which offers an encapsulation of the binary tool ELMO, in order to manipulate it easily in Python and SageMath script.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

servicethread.py 2.5KB

  1. import threading
  2. from protocol import Protocol, ClosureException
  3. class ServiceThread(threading.Thread):
  4. def run(self):
  5. self.execute()
  6. def execute(self):
  7. # Method where the service runs
  8. pass
  9. class OneShotServiceThread(ServiceThread):
  10. def __init__(self, ip, port, clientsocket):
  11. threading.Thread.__init__(self)
  12. self.ip = ip
  13. self.port = port
  14. self.clientsocket = clientsocket
  15. self.protocol = Protocol(clientsocket)
  16. def run(self):
  17. try:
  18. self.execute()
  19. except ClosureException:
  20. return
  21. def execute(self):
  22. # Method where the service runs
  23. pass
  24. class PermanentServiceThread(ServiceThread):
  25. def __init__(self):
  26. threading.Thread.__init__(self)
  27. self._is_running = True
  28. def is_running(self):
  29. return self._is_running
  30. def stop(self):
  31. self._is_running = False
  32. class ListeningThread(PermanentServiceThread):
  33. def __init__(self, host, port, threadclass, **kwargs):
  34. super().__init__()
  35. self.hostname = host
  36. self.port = port
  37. self.threadclass = threadclass
  38. self.kwargs = kwargs
  39. def execute(self):
  40. self.tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  41. self.tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  42. self.tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  43. # self.tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_ATTACH_REUSEPORT_CBPF, 1)
  44. self.tcpsock.bind((self.hostname, self.port))
  45. self.tcpsock.listen(5)
  46. print('[port][%s] Listening' % self.port)
  47. while self.is_running():
  48. try:
  49. (clientsocket, (ip, port)) = self.tcpsock.accept()
  50. print('[port][{}] Accepted: {} <=> {}'.format(
  51. self.port,
  52. clientsocket.getsockname(),
  53. clientsocket.getpeername(),
  54. ))
  55. newthread = self.threadclass(ip, port, clientsocket, **self.kwargs)
  56. newthread.start()
  57. except socket.timeout:
  58. pass
  59. def stop(self):
  60. super().stop()
  61. clientsocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  62. clientsocker.connect( (self.hostname, self.port) )
  63. self.tcpsock.close()
  64. print('[port][%s] Stop listening' % self.port)