如何允许 ws:// 而不是 localhost:// 龙卷风

How to allow ws:// instead of localhost:// for tornado

我有以下基本的龙卷风应用程序:

import tornado.web

class IndexHandler(tornado.web.RequestHandler):
    """Regular HTTP handler to serve the ping page"""
    def get(self):
        self.write("OK")

if __name__ == "__main__":

    app = tornado.web.Application([
    (r"/", IndexHandler), 
    ])
    app.listen(8000)
    print 'Listening on 0.0.0.0:8000'
    tornado.ioloop.IOLoop.instance().start()

这将在 "http://localhost:8000" 上 运行。我如何将它发送到 运行 并在 ws://localhost:8000 接受连接?

tornado.web.RequestHandler用于接受HTTP请求。对于 websockets,你需要使用 tornado.websocket.WebSocketHandler.


另一件需要注意的事情是您不能直接从浏览器访问 websocket url。也就是说,您不能在地址栏中键入 ws://localhost:8000 并期望连接到 websocket。这不是 websockets 的工作方式。

websocket 连接是升级连接。这意味着,您首先必须通过 HTTP 访问 url,然后使用 Javascript 升级到 websocket。

Mozilla Web Docs 查看有关如何使用 Javascript 连接到 websocket 的示例。