Async with Websockets

717 views
Skip to first unread message

rawberg

unread,
Mar 25, 2011, 5:50:18 AM3/25/11
to Tornado Web Server
Having trouble figuring out how to use websockets (via tornadio) and
asynchronously execute stuff that would otherwise block the server.

class ThingThatBlocks:

@classmethod
def block_things(cls):
logging.debug('going to sleep for 30 seconds')
sleep(30)
return 'did i block you too much?'

class SampleConnection(tornadio.SocketConnection):

def on_message(self, message):
if message['action'] == 'blocking':
self.async_callback(ThingThatBlocks.block_things)() # not
the magic answer i was hoping for
else:
self.send(message)

I'm pretty new to Python and still somewhat hopeful there is any easy
solution without having to learn all about threads and/or
multiprocessing... If not please feel free to shatter my dreams and
ignorance.

rawberg

unread,
Mar 25, 2011, 5:27:01 PM3/25/11
to Tornado Web Server
I tried following the chat demo a bit closer and came up with this.

class ThingThatBlocks:

@classmethod
def block_things(cls, callback):
logging.debug('going to sleep for 30 seconds')
sleep(30)
callback('did i block you too much?')

class SampleConnection(tornadio.SocketConnection):

@tornado.web.asynchronous
def on_message(self, message):
if message['action'] == 'blocking':

ThingThatBlocks.block_things(self.async_callback(self.on_async_response))
else:
self.send(message)

def on_async_response(self, message):
self.send(message)

Unfortunately this still completely blocks the server i.e. I can't
send and receive messages through the websocket while the async method
is running.

Ben Darnell

unread,
Mar 26, 2011, 2:54:10 PM3/26/11
to python-...@googlegroups.com, rawberg
async_callback() doesn't magically make synchronous code async, it just ensures that exceptions thrown after an async operation returns are handled appropriately (async_callback is mostly obsolete in tornado proper thanks to StackContext, but I don't know anything about tornadio).  If you need to do something that blocks for longer than you're willing to make the IOLoop wait you'll have to do it in another thread or process.  

-Ben

rawberg

unread,
Mar 26, 2011, 4:28:30 PM3/26/11
to Tornado Web Server
thanks for clearing that up Ben!
Reply all
Reply to author
Forward
0 new messages