server.py 6.2 KB

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