connection.py 7.1 KB

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