I have a basic Tornado websocket test:
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
print 'connection closed'
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
I want to be able to handle multiple connections (which it seems to do already) but also to be able to reference other connections. I don't see a way to identify and keep track of individual connections, just to be able to handle events on connection open, receipt of messages, and connection close.
[Edit]
Thought of creating a dict where the key is the Sec-websocket-key and and the value is the WSHandler object... thoughts? I'm not sure how dependable Sec-websocket-key is to be unique.
websocket — Bidirectional communication to the browser. Implementation of the WebSocket protocol. WebSockets allow for bidirectional communication between the browser and server.
The WebSockets protocol is over TCP only as currently defined. You could do UDP with Flash if you are willing to use a RTMFP (Real Time Messaging Flow Protocol) server.
The simplest method is just to keep a list or dict of WSHandler instances:
class WSHandler(tornado.websocket.WebSocketHandler):
clients = []
def open(self):
self.clients.append(self)
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
self.clients.remove(self)
print 'closed connection'
If you want to identify connections, e.g. by user, you'll probably have to send that information over the socket.
Cole Maclean asnwer is good as simple solution, when you just need list of all connections.
However, if you want something more complex, that can be monitored outside of WSHandler
instance - be brave do it like this:
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
self.id = uuid.uuid4()
external_storage[self.id] = {'id':self.id}
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
#Some message parsing here
if message.type == 'set_group':
external_storage[self.id]['group'] = message.group
print 'message received %s' % message
def on_close(self):
external_storage.remove(self.id)
print 'closed connection'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With