connection.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 class
  13. should implement the on*() event handlers.
  14. """
  15. def __init__(self, sock):
  16. """
  17. `sock` is a websocket instance which has completed its handshake.
  18. """
  19. self.sock = sock
  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. # Close the connection from this end as well
  61. self.close_frame_received = True
  62. code, reason = frame.unpack_close()
  63. # No more receiving data after a close message
  64. raise SocketClosed(code, reason)
  65. elif frame.opcode == OPCODE_PING:
  66. # Respond with a pong message with identical payload
  67. self.sock.send(ControlFrame(OPCODE_PONG, frame.payload))
  68. elif frame.opcode == OPCODE_PONG:
  69. # Assert that the PONG payload is identical to that of the PING
  70. if not self.ping_sent:
  71. raise PingError('received PONG while no PING was sent')
  72. self.ping_sent = False
  73. if frame.payload != self.ping_payload:
  74. raise PingError('received PONG with invalid payload')
  75. self.ping_payload = None
  76. self.onpong(frame.payload)
  77. def receive_forever(self):
  78. """
  79. Receive and handle messages in an endless loop. A message may consist
  80. of multiple data frames, but this is not visible for onmessage().
  81. Control messages (or control frames) are handled automatically.
  82. """
  83. while True:
  84. try:
  85. self.onmessage(self.receive())
  86. except SocketClosed as e:
  87. self.close(e.code, e.reason)
  88. break
  89. except socket.error as e:
  90. self.onerror(e)
  91. try:
  92. self.sock.close()
  93. except socket.error:
  94. pass
  95. self.onclose(None, '')
  96. break
  97. except Exception as e:
  98. self.onerror(e)
  99. def send_ping(self, payload=''):
  100. """
  101. Send a PING control frame with an optional payload.
  102. """
  103. self.sock.send(ControlFrame(OPCODE_PING, payload))
  104. self.ping_payload = payload
  105. self.ping_sent = True
  106. self.onping(payload)
  107. def close(self, code=None, reason=''):
  108. """
  109. Close the socket by sending a CLOSE frame and waiting for a response
  110. close message, unless such a message has already been received earlier
  111. (prior to calling this function, for example). The onclose() handler is
  112. called after the response has been received, but before the socket is
  113. actually closed.
  114. """
  115. # Send CLOSE frame
  116. payload = '' if code is None else struct.pack('!H', code) + reason
  117. self.sock.send(ControlFrame(OPCODE_CLOSE, payload))
  118. # Receive CLOSE frame
  119. if not self.close_frame_received:
  120. frame = self.sock.recv()
  121. if frame.opcode != OPCODE_CLOSE:
  122. raise ValueError('expected CLOSE frame, got %s' % frame)
  123. res_code, res_reason = frame.unpack_close()
  124. # FIXME: check if res_code == code and res_reason == reason?
  125. # FIXME: alternatively, keep receiving frames in a loop until a
  126. # CLOSE frame is received, so that a fragmented chain may arrive
  127. # fully first
  128. self.onclose(code, reason)
  129. self.sock.close()
  130. def onopen(self):
  131. """
  132. Called after the connection is initialized.
  133. """
  134. return NotImplemented
  135. def onmessage(self, message):
  136. """
  137. Called when a message is received. `message` is a Message object, which
  138. can be constructed from a single frame or multiple fragmented frames.
  139. """
  140. return NotImplemented
  141. def onping(self, payload):
  142. """
  143. Called after a PING control frame has been sent. This handler could be
  144. used to start a timeout handler for a PONG frame that is not received
  145. in time.
  146. """
  147. return NotImplemented
  148. def onpong(self, payload):
  149. """
  150. Called when a PONG control frame is received.
  151. """
  152. return NotImplemented
  153. def onclose(self, code, reason):
  154. """
  155. Called when the socket is closed by either end point.
  156. """
  157. return NotImplemented
  158. def onerror(self, e):
  159. """
  160. Handle a raised exception.
  161. """
  162. return NotImplemented