server.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. # Send a CLOSE frame so that the client connection will receive a
  80. # response CLOSE frame
  81. for client in self.clients:
  82. client.send_close_frame()
  83. # Wait for the CLOSE frames to be received. Wait for all threads in one
  84. # loop instead of joining separately, so that timeouts are not
  85. # propagated
  86. start_time = time.time()
  87. while time.time() - start_time <= self.max_join_time \
  88. and any(t.is_alive() for t in self.client_threads):
  89. time.sleep(0.050)
  90. # Close remaining sockets, this will trigger a socket.error in the
  91. # receive_forever() thread, causing the Connection.onclose() handler to
  92. # be invoked
  93. for client in self.clients:
  94. try:
  95. client.sock.close()
  96. except socket.error:
  97. pass
  98. # Wait for the onclose() handlers to finish
  99. for thread in self.client_threads:
  100. thread.join()
  101. def remove_client(self, client, code, reason):
  102. self.clients.remove(client)
  103. self.onclose(client, code, reason)
  104. def onopen(self, client):
  105. logging.debug('Opened socket to %s', client)
  106. def onmessage(self, client, message):
  107. logging.debug('Received %s from %s', message, client)
  108. def onping(self, client, payload):
  109. logging.debug('Sent ping "%s" to %s', payload, client)
  110. def onpong(self, client, payload):
  111. logging.debug('Received pong "%s" from %s', payload, client)
  112. def onclose(self, client, code, reason):
  113. msg = 'Closed socket to %s' % client
  114. if code is not None:
  115. msg += ' [%d]' % code
  116. if len(reason):
  117. msg += ': ' + reason
  118. logging.debug(msg)
  119. def onerror(self, client, e):
  120. logging.error(format_exc(e))
  121. class Client(Connection):
  122. def __init__(self, server, sock):
  123. self.server = server
  124. super(Client, self).__init__(sock)
  125. def __str__(self):
  126. try:
  127. return '<Client at %s:%d>' % self.sock.getpeername()
  128. except socket.error:
  129. return '<Client on closed socket>'
  130. def send(self, message, fragment_size=None, mask=False):
  131. logging.debug('Sending %s to %s', message, self)
  132. Connection.send(self, message, fragment_size=fragment_size, mask=mask)
  133. def onopen(self):
  134. self.server.onopen(self)
  135. def onmessage(self, message):
  136. self.server.onmessage(self, message)
  137. def onping(self, payload):
  138. self.server.onping(self, payload)
  139. def onpong(self, payload):
  140. self.server.onpong(self, payload)
  141. def onclose(self, code, reason):
  142. self.server.remove_client(self, code, reason)
  143. def onerror(self, e):
  144. self.server.onerror(self, e)
  145. if __name__ == '__main__':
  146. import sys
  147. port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
  148. Server(port, loglevel=logging.DEBUG).run()