Home  >  Q&A  >  body text

python - 关于基于tornado的websocket服务在本机上调试的问题

我启动了一个简单的tornado服务器,代码如下

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import json

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")

class ChatHandler(tornado.websocket.WebSocketHandler):
    users = set()

    def open(self):
        ChatHandler.users.add(self)

    def on_message(self, message):
        jsonObject = json.loads(message)
        for user in ChatHandler.users:
            print(user)
            self.write_message(jsonObject["message"])

    def on_close(self):
        ChatHandler.users.remove(self)

if __name__ == '__main__':
    app = tornado.web.Application(
        handlers=[
            (r"/", IndexHandler),
            (r"/ws",ChatHandler)
        ]
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(12345)
    tornado.ioloop.IOLoop.instance().start()

现在的问题是,我分别在edge和chrome浏览器中通过localhost:12345访问的时候,当在某一个浏览器中发送消息的时候,想实现的效果是两个页面都能收到该消息。但实际的情况是只有发出消息的浏览器页面会收到两个MessageEvent,请问该如何解决这个问题?

怪我咯怪我咯2741 days ago488

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:32:52

    self.write_message(jsonObject["message"])

    It means that the message is sent to whomever it is received from. Several people have posted online several times.

    What you need is, no matter who you receive the message from, send a copy to everyone online. Who is online? Of course it is being iterated user.

    reply
    0
  • Cancelreply