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