我想在Tornado服务器和Javascript客户端之间建立一个简单的双向通信。
当我运行服务器,然后打开页面时,服务器按预期打印出“get”。但是,当服务器发回一些东西时,onmessage事件似乎永远不会在客户端中触发。此外,Javascript控制台会产生以下错误:
WebSocket connection to 'ws://localhost:8888/' failed: Error during WebSocket handshake: Unexpected response code: 200
我不知道我在这里做错了什么。
Python服务器(tornadoserver.py):
import tornado.ioloop
import tornado.web
class Hello(tornado.web.RequestHandler):
def get(self):
print("get")
self.write("Hello, world")
self.flush()
application = tornado.web.Application([
(r"/", Hello),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Javascript客户端(tornado.html):
<script>
ws = new WebSocket("ws://localhost:8888/");
ws.onmessage = function(e) {
alert('message received: ' + e.data);
};
</script>
答案 0 :(得分:5)
您需要一个单独的WebSocketHandler实例映射到应用程序中的单独URL。所以你的“tornado.html”应该映射到URL“/”,你的Javascript应该连接到一个WebSocketHandler,监听像“/ websocket”这样的URL。试试这个:
import tornado.ioloop
import tornado.web
import tornado.websocket
class Hello(tornado.websocket.WebSocketHandler):
def open(self):
self.write_message("Hello, world")
def on_message(self, message):
pass
def on_close(self):
pass
class Main(tornado.web.RequestHandler):
def get(self):
# This could be a template, too.
self.write('''
<script>
ws = new WebSocket("ws://localhost:8888/websocket");
ws.onmessage = function(e) {
alert('message received: ' + e.data);
};
</script>''')
application = tornado.web.Application([
(r"/", Main),
(r"/websocket", Hello),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()