connection.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import struct
  2. import socket
  3. from frame import ControlFrame, OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG, \
  4. OPCODE_CONTINUATION
  5. from message import create_message
  6. from errors import SocketClosed, PingError
  7. class Connection(object):
  8. """
  9. A `Connection` uses a `websocket` instance to send and receive (optionally
  10. fragmented) messages, which are `Message` instances. Control frames are
  11. handled automatically in the way specified by RFC 6455.
  12. To use the `Connection` class, it should be extended and the extending
  13. class should implement the on*() event handlers.
  14. Example of an echo server (sends back what it receives):
  15. >>> import twspy
  16. >>> class EchoConnection(twspy.Connection):
  17. >>> def onopen(self):
  18. >>> print 'Connection opened at %s:%d' % self.sock.getpeername()
  19. >>> def onmessage(self, message):
  20. >>> print 'Received message "%s"' % message.payload
  21. >>> self.send(twspy.TextMessage(message.payload))
  22. >>> def onclose(self, message):
  23. >>> print 'Connection closed'
  24. >>> server = twspy.websocket()
  25. >>> server.bind(('', 8000))
  26. >>> server.listen()
  27. >>> while True:
  28. >>> client, addr = server.accept()
  29. >>> EchoConnection(client).receive_forever()
  30. """
  31. def __init__(self, sock):
  32. """
  33. `sock` is a websocket instance which has completed its handshake.
  34. """
  35. self.sock = sock
  36. self.close_frame_sent = False
  37. self.close_frame_received = False
  38. self.ping_sent = False
  39. self.ping_payload = None
  40. self.onopen()
  41. def send(self, message, fragment_size=None, mask=False):
  42. """
  43. Send a message. If `fragment_size` is specified, the message is
  44. fragmented into multiple frames whose payload size does not extend
  45. `fragment_size`.
  46. """
  47. if fragment_size is None:
  48. self.sock.send(message.frame(mask=mask))
  49. else:
  50. self.sock.send(*message.fragment(fragment_size, mask=mask))
  51. def recv(self):
  52. """
  53. Receive a message. A message may consist of multiple (ordered) data
  54. frames. A control frame may be delivered at any time, also when
  55. expecting the next continuation frame of a fragmented message. These
  56. control frames are handled immediately by handle_control_frame().
  57. """
  58. fragments = []
  59. while not len(fragments) or not fragments[-1].final:
  60. frame = self.sock.recv()
  61. if isinstance(frame, ControlFrame):
  62. self.handle_control_frame(frame)
  63. elif len(fragments) and frame.opcode != OPCODE_CONTINUATION:
  64. raise ValueError('expected continuation/control frame, got %s '
  65. 'instead' % frame)
  66. else:
  67. fragments.append(frame)
  68. payload = bytearray()
  69. for f in fragments:
  70. payload += f.payload
  71. return create_message(fragments[0].opcode, payload)
  72. def handle_control_frame(self, frame):
  73. """
  74. Handle a control frame as defined by RFC 6455.
  75. """
  76. if frame.opcode == OPCODE_CLOSE:
  77. # Close the connection from this end as well
  78. self.close_frame_received = True
  79. code, reason = frame.unpack_close()
  80. # No more receiving data after a close message
  81. raise SocketClosed(code, reason)
  82. elif frame.opcode == OPCODE_PING:
  83. # Respond with a pong message with identical payload
  84. self.sock.send(ControlFrame(OPCODE_PONG, frame.payload))
  85. elif frame.opcode == OPCODE_PONG:
  86. # Assert that the PONG payload is identical to that of the PING
  87. if not self.ping_sent:
  88. raise PingError('received PONG while no PING was sent')
  89. self.ping_sent = False
  90. if frame.payload != self.ping_payload:
  91. raise PingError('received PONG with invalid payload')
  92. self.ping_payload = None
  93. self.onpong(frame.payload)
  94. def receive_forever(self):
  95. """
  96. Receive and handle messages in an endless loop. A message may consist
  97. of multiple data frames, but this is not visible for onmessage().
  98. Control messages (or control frames) are handled automatically.
  99. """
  100. while True:
  101. try:
  102. self.onmessage(self.recv())
  103. except SocketClosed as e:
  104. self.close(e.code, e.reason)
  105. break
  106. except socket.error as e:
  107. self.onerror(e)
  108. try:
  109. self.sock.close()
  110. except socket.error:
  111. pass
  112. self.onclose(None, '')
  113. break
  114. except Exception as e:
  115. self.onerror(e)
  116. def send_ping(self, payload=''):
  117. """
  118. Send a PING control frame with an optional payload.
  119. """
  120. self.sock.send(ControlFrame(OPCODE_PING, payload))
  121. self.ping_payload = payload
  122. self.ping_sent = True
  123. self.onping(payload)
  124. def send_close_frame(self, code=None, reason=''):
  125. """
  126. Send a CLOSE control frame.
  127. """
  128. payload = '' if code is None else struct.pack('!H', code) + reason
  129. self.sock.send(ControlFrame(OPCODE_CLOSE, payload))
  130. self.close_frame_sent = True
  131. def close(self, code=None, reason=''):
  132. """
  133. Close the socket by sending a CLOSE frame and waiting for a response
  134. close message, unless such a message has already been received earlier
  135. (prior to calling this function, for example). The onclose() handler is
  136. called after the response has been received, but before the socket is
  137. actually closed.
  138. """
  139. # Send CLOSE frame
  140. if not self.close_frame_sent:
  141. self.send_close_frame(code, reason)
  142. # Receive CLOSE frame
  143. if not self.close_frame_received:
  144. frame = self.sock.recv()
  145. if frame.opcode != OPCODE_CLOSE:
  146. raise ValueError('expected CLOSE frame, got %s' % frame)
  147. self.close_frame_received = True
  148. res_code, res_reason = frame.unpack_close()
  149. # FIXME: check if res_code == code and res_reason == reason?
  150. # FIXME: alternatively, keep receiving frames in a loop until a
  151. # CLOSE frame is received, so that a fragmented chain may arrive
  152. # fully first
  153. self.onclose(code, reason)
  154. self.sock.close()
  155. def onopen(self):
  156. """
  157. Called after the connection is initialized.
  158. """
  159. return NotImplemented
  160. def onmessage(self, message):
  161. """
  162. Called when a message is received. `message` is a Message object, which
  163. can be constructed from a single frame or multiple fragmented frames.
  164. """
  165. return NotImplemented
  166. def onping(self, payload):
  167. """
  168. Called after a PING control frame has been sent. This handler could be
  169. used to start a timeout handler for a PONG frame that is not received
  170. in time.
  171. """
  172. return NotImplemented
  173. def onpong(self, payload):
  174. """
  175. Called when a PONG control frame is received.
  176. """
  177. return NotImplemented
  178. def onclose(self, code, reason):
  179. """
  180. Called when the socket is closed by either end point.
  181. """
  182. return NotImplemented
  183. def onerror(self, e):
  184. """
  185. Handle a raised exception.
  186. """
  187. return NotImplemented