server.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import socket
  2. import logging
  3. import time
  4. from traceback import format_exc
  5. from threading import Thread
  6. from ssl import SSLError
  7. from websocket import websocket
  8. from connection import Connection
  9. from frame import CLOSE_NORMAL
  10. from errors import HandshakeError
  11. class Server(object):
  12. """
  13. Websocket server, manages multiple client connections.
  14. Example usage:
  15. >>> import twspy
  16. >>> class GameServer(twspy.Server):
  17. >>> def onopen(self, client):
  18. >>> # client connected
  19. >>> def onclose(self, client):
  20. >>> # client disconnected
  21. >>> def onmessage(self, client, message):
  22. >>> # handle message from client
  23. >>> GameServer(8000).run()
  24. """
  25. def __init__(self, port, hostname='', loglevel=logging.INFO, protocols=[],
  26. secure=False, max_join_time=2.0, **kwargs):
  27. """
  28. Constructor for a simple websocket server.
  29. `hostname` and `port` form the address to bind the websocket to.
  30. `loglevel` values should be imported from the logging module.
  31. logging.INFO only shows server start/stop messages, logging.DEBUG shows
  32. clients (dis)connecting and messages being sent/received.
  33. `protocols` is a list of supported protocols, passed directly to the
  34. websocket constructor.
  35. `secure` is a flag indicating whether the server is SSL enabled. In
  36. this case, `keyfile` and `certfile` must be specified. Any additional
  37. keyword arguments are passed to websocket.enable_ssl (and thus to
  38. ssl.wrap_socket).
  39. `max_join_time` is the maximum time (in seconds) to wait for client
  40. responses after sending CLOSE frames, it defaults to 2 seconds.
  41. """
  42. logging.basicConfig(level=loglevel,
  43. format='%(asctime)s: %(levelname)s: %(message)s',
  44. datefmt='%H:%M:%S')
  45. scheme = 'wss' if secure else 'ws'
  46. logging.info('Starting server at %s://%s:%d', scheme, hostname, port)
  47. self.sock = websocket()
  48. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  49. if secure:
  50. self.sock.enable_ssl(server_side=True, **kwargs)
  51. self.sock.bind((hostname, port))
  52. self.sock.listen(5)
  53. self.clients = []
  54. self.client_threads = []
  55. self.protocols = protocols
  56. self.max_join_time = max_join_time
  57. def run(self):
  58. while True:
  59. try:
  60. sock, address = self.sock.accept()
  61. client = Client(self, sock)
  62. self.clients.append(client)
  63. logging.debug('Registered client %s', client)
  64. thread = Thread(target=client.receive_forever)
  65. thread.daemon = True
  66. thread.start()
  67. self.client_threads.append(thread)
  68. except SSLError as e:
  69. logging.error('SSL error: %s', e)
  70. except HandshakeError as e:
  71. logging.error('Invalid request: %s', e.message)
  72. except KeyboardInterrupt:
  73. logging.info('Received interrupt, stopping server...')
  74. break
  75. except Exception as e:
  76. logging.error(format_exc(e))
  77. self.quit_gracefully()
  78. def quit_gracefully(self):
  79. for client in self.clients:
  80. client.send_close_frame()
  81. start_time = time.time()
  82. while time.time() - start_time <= self.max_join_time \
  83. and any(t.is_alive() for t in self.client_threads):
  84. time.sleep(0.050)
  85. def remove_client(self, client, code, reason):
  86. self.clients.remove(client)
  87. self.onclose(client, code, reason)
  88. def onopen(self, client):
  89. logging.debug('Opened socket to %s', client)
  90. def onmessage(self, client, message):
  91. logging.debug('Received %s from %s', message, client)
  92. def onping(self, client, payload):
  93. logging.debug('Sent ping "%s" to %s', payload, client)
  94. def onpong(self, client, payload):
  95. logging.debug('Received pong "%s" from %s', payload, client)
  96. def onclose(self, client, code, reason):
  97. msg = 'Closed socket to %s' % client
  98. if code is not None:
  99. msg += ' [%d]' % code
  100. if len(reason):
  101. msg += ': ' + reason
  102. logging.debug(msg)
  103. def onerror(self, client, e):
  104. logging.error(format_exc(e))
  105. class Client(Connection):
  106. def __init__(self, server, sock):
  107. self.server = server
  108. super(Client, self).__init__(sock)
  109. def __str__(self):
  110. try:
  111. return '<Client at %s:%d>' % self.sock.getpeername()
  112. except socket.error:
  113. return '<Client on closed socket>'
  114. def send(self, message, fragment_size=None, mask=False):
  115. logging.debug('Sending %s to %s', message, self)
  116. Connection.send(self, message, fragment_size=fragment_size, mask=mask)
  117. def onopen(self):
  118. self.server.onopen(self)
  119. def onmessage(self, message):
  120. self.server.onmessage(self, message)
  121. def onping(self, payload):
  122. self.server.onping(self, payload)
  123. def onpong(self, payload):
  124. self.server.onpong(self, payload)
  125. def onclose(self, code, reason):
  126. self.server.remove_client(self, code, reason)
  127. def onerror(self, e):
  128. self.server.onerror(self, e)
  129. if __name__ == '__main__':
  130. import sys
  131. port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
  132. Server(port, loglevel=logging.DEBUG).run()