Skip to content

Commit

Permalink
Merge remote-tracking branch 'Caligatio/ws_message_callback'
Browse files Browse the repository at this point in the history
Conflicts:
	tornado/websocket.py
  • Loading branch information
bdarnell committed Jan 24, 2015
2 parents bff8603 + 1e8582f commit 73ffb31
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions tornado/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,13 +860,15 @@ class WebSocketClientConnection(simple_httpclient._HTTPConnection):
This class should not be instantiated directly; use the
`websocket_connect` function instead.
"""
def __init__(self, io_loop, request, compression_options=None):
def __init__(self, io_loop, request, on_message_callback=None,
compression_options=None):
self.compression_options = compression_options
self.connect_future = TracebackFuture()
self.protocol = None
self.read_future = None
self.read_queue = collections.deque()
self.key = base64.b64encode(os.urandom(16))
self._on_message_callback = on_message_callback

scheme, sep, rest = request.url.partition(':')
scheme = {'ws': 'http', 'wss': 'https'}[scheme]
Expand Down Expand Up @@ -953,6 +955,9 @@ def write_message(self, message, binary=False):
def read_message(self, callback=None):
"""Reads a message from the WebSocket server.
If on_message_callback was specified at WebSocket
initialization, this function will never return messages
Returns a future whose result is the message, or None
if the connection is closed. If a callback argument
is given it will be called with the future when it is
Expand All @@ -969,7 +974,9 @@ def read_message(self, callback=None):
return future

def on_message(self, message):
if self.read_future is not None:
if self._on_message_callback:
self._on_message_callback(message)
elif self.read_future is not None:
self.read_future.set_result(message)
self.read_future = None
else:
Expand All @@ -984,7 +991,7 @@ def get_websocket_protocol(self):


def websocket_connect(url, io_loop=None, callback=None, connect_timeout=None,
compression_options=None):
on_message_callback=None, compression_options=None):
"""Client-side websocket support.
Takes a url and returns a Future whose result is a
Expand All @@ -1011,7 +1018,9 @@ def websocket_connect(url, io_loop=None, callback=None, connect_timeout=None,
request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout)
request = httpclient._RequestProxy(
request, httpclient.HTTPRequest._DEFAULTS)
conn = WebSocketClientConnection(io_loop, request, compression_options)
conn = WebSocketClientConnection(io_loop, request,
on_message_callback=on_message_callback,
compression_options=compression_options)
if callback is not None:
io_loop.add_future(conn.connect_future, callback)
return conn.connect_future

0 comments on commit 73ffb31

Please sign in to comment.