我正在运行一个非常简单的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连接到这个
^{pr2}$在控制台里我看到了
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()
之前,我不会收到您问题中所示的连接关闭消息。(龙卷风4.4.1)。在不管问题是什么,它似乎在您的环境中,而不是您的代码中。在
相关问题 更多 >
编程相关推荐