server.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 errors import HandshakeError
  10. class Server(object):
  11. """
  12. Websocket server, manages multiple client connections.
  13. Example usage:
  14. >>> import twspy
  15. >>> class EchoServer(twspy.Server):
  16. >>> def onopen(self, client):
  17. >>> print 'Client %s connected' % client
  18. >>> def onmessage(self, client, message):
  19. >>> print 'Received message "%s"' % message.payload
  20. >>> client.send(twspy.TextMessage(message.payload))
  21. >>> def onclose(self, client):
  22. >>> print 'Client %s disconnected' % client
  23. >>> EchoServer(('', 8000)).run()
  24. """
  25. def __init__(self, address, loglevel=logging.INFO, protocols=[],
  26. secure=False, max_join_time=2.0, **kwargs):
  27. """
  28. Constructor for a simple web socket server.
  29. `address` is a (hostname, port) tuple to bind the web socket 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` and `extensions` are passed directly to the websocket
  34. 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. hostname, port = address
  47. logging.info('Starting server at %s://%s:%d', scheme, hostname, port)
  48. self.sock = websocket(protocols=protocols, extensions=extensions)
  49. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  50. if secure:
  51. self.sock.enable_ssl(server_side=True, **kwargs)
  52. self.sock.bind(address)
  53. self.sock.listen(5)
  54. self.clients = []
  55. self.client_threads = []
  56. self.protocols = protocols
  57. self.max_join_time = max_join_time
  58. def run(self):
  59. while True:
  60. try:
  61. sock, address = self.sock.accept()
  62. client = Client(self, sock)
  63. self.clients.append(client)
  64. logging.debug('Registered client %s', client)
  65. thread = Thread(target=client.receive_forever)
  66. thread.daemon = True
  67. thread.start()
  68. self.client_threads.append(thread)
  69. except SSLError as e:
  70. logging.error('SSL error: %s', e)
  71. except HandshakeError as e:
  72. logging.error('Invalid request: %s', e.message)
  73. except KeyboardInterrupt:
  74. logging.info('Received interrupt, stopping server...')
  75. break
  76. except Exception as e:
  77. logging.error(format_exc(e))
  78. self.quit_gracefully()
  79. def quit_gracefully(self):
  80. # Send a CLOSE frame so that the client connection will receive a
  81. # response CLOSE frame
  82. for client in self.clients:
  83. client.send_close_frame()
  84. # Wait for the CLOSE frames to be received. Wait for all threads in one
  85. # loop instead of joining separately, so that timeouts are not
  86. # propagated
  87. start_time = time.time()
  88. while time.time() - start_time <= self.max_join_time \
  89. and any(t.is_alive() for t in self.client_threads):
  90. time.sleep(0.050)
  91. # Close remaining sockets, this will trigger a socket.error in the
  92. # receive_forever() thread, causing the Connection.onclose() handler to
  93. # be invoked
  94. for client in self.clients:
  95. try:
  96. client.sock.close()
  97. except socket.error:
  98. pass
  99. # Wait for the onclose() handlers to finish
  100. for thread in self.client_threads:
  101. thread.join()
  102. def remove_client(self, client, code, reason):
  103. self.clients.remove(client)
  104. self.onclose(client, code, reason)
  105. def onopen(self, client):
  106. logging.debug('Opened socket to %s', client)
  107. def onmessage(self, client, message):
  108. logging.debug('Received %s from %s', message, client)
  109. def onping(self, client, payload):
  110. logging.debug('Sent ping "%s" to %s', payload, client)
  111. def onpong(self, client, payload):
  112. logging.debug('Received pong "%s" from %s', payload, client)
  113. def onclose(self, client, code, reason):
  114. msg = 'Closed socket to %s' % client
  115. if code is not None:
  116. msg += ' [%d]' % code
  117. if len(reason):
  118. msg += ': ' + reason
  119. logging.debug(msg)
  120. def onerror(self, client, e):
  121. logging.error(format_exc(e))
  122. class Client(Connection):
  123. def __init__(self, server, sock):
  124. self.server = server
  125. super(Client, self).__init__(sock)
  126. def __str__(self):
  127. try:
  128. return '<Client at %s:%d>' % self.sock.getpeername()
  129. except socket.error:
  130. return '<Client on closed socket>'
  131. def send(self, message, fragment_size=None, mask=False):
  132. logging.debug('Sending %s to %s', message, self)
  133. Connection.send(self, message, fragment_size=fragment_size, mask=mask)
  134. def onopen(self):
  135. self.server.onopen(self)
  136. def onmessage(self, message):
  137. self.server.onmessage(self, message)
  138. def onping(self, payload):
  139. self.server.onping(self, payload)
  140. def onpong(self, payload):
  141. self.server.onpong(self, payload)
  142. def onclose(self, code, reason):
  143. self.server.remove_client(self, code, reason)
  144. def onerror(self, e):
  145. self.server.onerror(self, e)
  146. if __name__ == '__main__':
  147. import sys
  148. port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
  149. Server(('', port), loglevel=logging.DEBUG).run()