connection.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import socket
  2. from frame import ControlFrame, OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG, \
  3. OPCODE_CONTINUATION, create_close_frame
  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
  12. class should implement the on*() event handlers.
  13. Example of an echo server (sends back what it receives):
  14. >>> import wspy
  15. >>> class EchoConnection(wspy.Connection):
  16. >>> def onopen(self):
  17. >>> print 'Connection opened at %s:%d' % self.sock.getpeername()
  18. >>> def onmessage(self, message):
  19. >>> print 'Received message "%s"' % message.payload
  20. >>> self.send(wspy.TextMessage(message.payload))
  21. >>> def onclose(self, code, reason):
  22. >>> print 'Connection closed'
  23. >>> server = wspy.websocket()
  24. >>> server.bind(('', 8000))
  25. >>> server.listen()
  26. >>> while True:
  27. >>> client, addr = server.accept()
  28. >>> EchoConnection(client).receive_forever()
  29. """
  30. def __init__(self, sock):
  31. """
  32. `sock` is a websocket instance which has completed its handshake.
  33. """
  34. self.sock = sock
  35. self.close_frame_sent = False
  36. self.close_frame_received = False
  37. self.ping_sent = False
  38. self.ping_payload = None
  39. self.hooks_send = []
  40. self.hooks_recv = []
  41. self.onopen()
  42. def message_to_frames(self, message, fragment_size=None, mask=False):
  43. for hook in self.hooks_send:
  44. message = hook(message)
  45. if fragment_size is None:
  46. yield message.frame(mask=mask)
  47. else:
  48. for frame in message.fragment(fragment_size, mask=mask):
  49. yield frame
  50. def send(self, message, fragment_size=None, mask=False):
  51. """
  52. Send a message. If `fragment_size` is specified, the message is
  53. fragmented into multiple frames whose payload size does not extend
  54. `fragment_size`.
  55. """
  56. for frame in self.message_to_frames(message, fragment_size, mask):
  57. self.send_frame(frame)
  58. def send_frame(self, frame, callback=None):
  59. self.sock.send(frame)
  60. if callback:
  61. callback()
  62. def recv(self):
  63. """
  64. Receive a message. A message may consist of multiple (ordered) data
  65. frames. A control frame may be delivered at any time, also when
  66. expecting the next continuation frame of a fragmented message. These
  67. control frames are handled immediately by handle_control_frame().
  68. """
  69. fragments = []
  70. while not len(fragments) or not fragments[-1].final:
  71. frame = self.sock.recv()
  72. if isinstance(frame, ControlFrame):
  73. self.handle_control_frame(frame)
  74. elif len(fragments) > 0 and frame.opcode != OPCODE_CONTINUATION:
  75. raise ValueError('expected continuation/control frame, got %s '
  76. 'instead' % frame)
  77. else:
  78. fragments.append(frame)
  79. return self.concat_fragments(fragments)
  80. def concat_fragments(self, fragments):
  81. payload = bytearray()
  82. for f in fragments:
  83. payload += f.payload
  84. message = create_message(fragments[0].opcode, payload)
  85. for hook in self.hooks_recv:
  86. message = hook(message)
  87. return message
  88. def handle_control_frame(self, frame):
  89. """
  90. Handle a control frame as defined by RFC 6455.
  91. """
  92. if frame.opcode == OPCODE_CLOSE:
  93. self.close_frame_received = True
  94. code, reason = frame.unpack_close()
  95. if self.close_frame_sent:
  96. self.onclose(code, reason)
  97. self.sock.close()
  98. raise SocketClosed(True)
  99. else:
  100. self.close_params = (code, reason)
  101. self.send_close_frame(code, reason)
  102. elif frame.opcode == OPCODE_PING:
  103. # Respond with a pong message with identical payload
  104. self.send_frame(ControlFrame(OPCODE_PONG, frame.payload))
  105. elif frame.opcode == OPCODE_PONG:
  106. # Assert that the PONG payload is identical to that of the PING
  107. if not self.ping_sent:
  108. raise PingError('received PONG while no PING was sent')
  109. self.ping_sent = False
  110. if frame.payload != self.ping_payload:
  111. raise PingError('received PONG with invalid payload')
  112. self.ping_payload = None
  113. self.onpong(frame.payload)
  114. def receive_forever(self):
  115. """
  116. Receive and handle messages in an endless loop. A message may consist
  117. of multiple data frames, but this is not visible for onmessage().
  118. Control messages (or control frames) are handled automatically.
  119. """
  120. while True:
  121. try:
  122. self.onmessage(self.recv())
  123. except (KeyboardInterrupt, SystemExit, SocketClosed):
  124. break
  125. except Exception as e:
  126. self.onerror(e)
  127. self.onclose(None, 'error: %s' % e)
  128. try:
  129. self.sock.close()
  130. except socket.error:
  131. pass
  132. raise e
  133. def send_ping(self, payload=''):
  134. """
  135. Send a PING control frame with an optional payload.
  136. """
  137. self.send_frame(ControlFrame(OPCODE_PING, payload),
  138. lambda: self.onping(payload))
  139. self.ping_payload = payload
  140. self.ping_sent = True
  141. def send_close_frame(self, code, reason):
  142. self.send_frame(create_close_frame(code, reason))
  143. self.close_frame_sent = True
  144. self.shutdown_write()
  145. def shutdown_write(self):
  146. if self.close_frame_received:
  147. self.onclose(*self.close_params)
  148. self.sock.close()
  149. raise SocketClosed(False)
  150. else:
  151. self.sock.shutdown(socket.SHUT_WR)
  152. def close(self, code=None, reason=''):
  153. """
  154. Close the socket by sending a CLOSE frame and waiting for a response
  155. close message, unless such a message has already been received earlier
  156. (prior to calling this function, for example). The onclose() handler is
  157. called after the response has been received, but before the socket is
  158. actually closed.
  159. """
  160. self.send_close_frame(code, reason)
  161. frame = self.sock.recv()
  162. if frame.opcode != OPCODE_CLOSE:
  163. raise ValueError('expected CLOSE frame, got %s' % frame)
  164. self.handle_control_frame(frame)
  165. def add_hook(self, send=None, recv=None, prepend=False):
  166. """
  167. Add a pair of send and receive hooks that are called for each frame
  168. that is sent or received. A hook is a function that receives a single
  169. argument - a Message instance - and returns a `Message` instance as
  170. well.
  171. `prepend` is a flag indicating whether the send hook is prepended to
  172. the other send hooks.
  173. For example, to add an automatic JSON conversion to messages and
  174. eliminate the need to contruct TextMessage instances to all messages:
  175. >>> import wspy, json
  176. >>> conn = Connection(...)
  177. >>> conn.add_hook(lambda data: tswpy.TextMessage(json.dumps(data)),
  178. >>> lambda message: json.loads(message.payload))
  179. >>> conn.send({'foo': 'bar'}) # Sends text message {"foo":"bar"}
  180. >>> conn.recv() # May be dict(foo='bar')
  181. Note that here `prepend=True`, so that data passed to `send()` is first
  182. encoded and then packed into a frame. Of course, one could also decide
  183. to add the base64 hook first, or to return a new `Frame` instance with
  184. base64-encoded data.
  185. """
  186. if send:
  187. self.hooks_send.insert(0 if prepend else -1, send)
  188. if recv:
  189. self.hooks_recv.insert(-1 if prepend else 0, recv)
  190. def onopen(self):
  191. """
  192. Called after the connection is initialized.
  193. """
  194. return NotImplemented
  195. def onmessage(self, message):
  196. """
  197. Called when a message is received. `message` is a Message object, which
  198. can be constructed from a single frame or multiple fragmented frames.
  199. """
  200. return NotImplemented
  201. def onping(self, payload):
  202. """
  203. Called after a PING control frame has been sent. This handler could be
  204. used to start a timeout handler for a PONG frame that is not received
  205. in time.
  206. """
  207. return NotImplemented
  208. def onpong(self, payload):
  209. """
  210. Called when a PONG control frame is received.
  211. """
  212. return NotImplemented
  213. def onclose(self, code, reason):
  214. """
  215. Called when the socket is closed by either end point.
  216. """
  217. return NotImplemented
  218. def onerror(self, e):
  219. """
  220. Handle a raised exception.
  221. """
  222. return NotImplemented