【问题标题】:Web Socket not connecting to tornado serverWeb Socket 未连接到龙卷风服务器
【发布时间】:2013-10-26 17:10:54
【问题描述】:

我正在使用 python tornado 框架为我正在编写的游戏编写一个小型 Web 服务器。获取请求工作正常,但是,当我尝试创建 websocket 连接时,我在浏览器中收到此错误:

这是我的 javascript 代码:

    var ws = new WebSocket("ws://localhost:8888/ws");
    ws.onopen = function() {
            ws.send("ping");
    };

这里是python服务器的代码:

class StateQueryHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        state.players = state.players + 1
        self.write(state.players)
        print("socket opened")

。 . .

application = tornado.web.Application([
    (r"/ws", StateQueryHandler),#websocket endpoint
    (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "../client"})
])
server = tornado.httpserver.HTTPServer(application)
server.listen(8888)
tornado.ioloop.PeriodicCallback(state.update, 250).start()
tornado.ioloop.IOLoop.instance().start()

谁能告诉我出了什么问题?我是否必须在服务器端做任何额外的事情来保持 tcp 连接处于活动状态?

【问题讨论】:

    标签: javascript python websocket tornado


    【解决方案1】:

    试试这个:

    class StateQueryHandler(tornado.websocket.WebSocketHandler):
        def open(self):
            state.players = state.players + 1
            self.write_message(state.players)
            print("socket opened")
    

    你需要调用方法write_message,而不是write。

    查看文档了解更多信息:http://www.tornadoweb.org/en/branch2.4/websocket.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      相关资源
      最近更新 更多