![](/img/trans.png)
[英]What is the 'Hello, World' for the Javascript InfoVis Toolkit?
[英]Hello world with Tornado and Javascript client
我想在 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>
您需要一個單獨的WebSocketHandler實例映射到應用程序中的單獨 URL。 因此,您的“tornado.html”應該映射到 URL“/”,並且您的 Javascript 應該連接到監聽諸如“/websocket”之類的 URL 的 WebSocketHandler。 嘗試這個:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.