Tornado:识别/跟踪 websockets 的连接? [英] Tornado: Identify / track connections of websockets?

查看:20
本文介绍了Tornado:识别/跟踪 websockets 的连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的 Tornado websocket 测试:

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.


想创建一个字典,其中键是 Sec-websocket-key,值是 WSHandler 对象......想法?我不确定 Sec-websocket-key 的唯一性有多可靠.


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.

推荐答案

最简单的方法就是保留一个 WSHandler 实例的列表或字典:

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.

这篇关于Tornado:识别/跟踪 websockets 的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆