我正在运行一个非常简单的 echo websocket 服务器,如下所示:
#!/usr/bin/python
import datetime
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
clients = []
def open(self):
print('new connection')
self.write_message("Hello World")
WSHandler.clients.append(self)
def on_message(self, message):
print('message received %s' % message)
self.write_message('ECHO: ' + message)
def on_close(self):
print('connection closed')
WSHandler.clients.remove(self)
@classmethod
def write_to_clients(cls):
print("Writing to clients")
for client in cls.clients:
client.write_message("Hi there!")
def check_origin(self, origin):
return True
application = tornado.web.Application([
(r'/websocket', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(80)
tornado.ioloop.IOLoop.instance().start()
我正在使用 javascript 连接到它,如下所示
var ws = new WebSocket("ws://localhost:80/websocket");
在控制台我看到了
new connection
connection closed
我不明白的是为什么我在控制台中看到 connection closed
。客户端还表示连接已关闭,但我看不出有什么好的理由。任何帮助将不胜感激。要以管理员身份复制运行 python 代码,请打开任何 JS 控制台并输入 JS 代码。我想要的结果是不立即关闭套接字。这在某种程度上基于我在 tornado docs 中阅读的内容.
编辑 通过在open
方法中注释掉self.write_message("Hello World")
更新,连接不会关闭。但是,现在运行文档中的示例代码会产生一些有趣的东西。
var ws = new WebSocket("ws://localhost:80/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
服务器端输出是
new connection
message received Hello, world
connection closed
客户端没有预期的相应告警
新问题与旧问题相同,即为什么服务器显示connection closed
?看起来 self.write_message
可能是罪魁祸首。
最佳答案
不确定这是否有任何帮助,但我运行了您的代码,它的工作方式与您期望的完全一样。在我调用 ws.close()
之前,我没有收到您问题中指示的连接关闭消息。 ( Tornado 4.4.1)。
无论问题是什么,它似乎出在您的环境中,而不是您的代码中。
关于javascript - 连接在打开时立即关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38661067/