这让我发疯。我正在使用 Tornado 3.2 和 python 2.7。我已经在我的测试机 (Windows) 和我的 Linux 机器上都试过了。我只是在用(我认为是)一个简单的聊天室应用程序试水。这是到目前为止的代码:
class LobbyWS(tornado.websocket.WebSocketHandler):
clients = []
def open(self, *args):
self.stream.set_nodelay(True)
self.ping('one')
LobbyWS.clients.append(self)
print 'opening %s' % self
def on_pong(self, data):
print 'got pong', data
def on_message(self, message):
print "Client %s received a message : %s" % (self, message)
for client in LobbyWS.clients:
client.write_message(message)
def on_close(self):
print "Client %s closed." % self
LobbyWS.clients.remove(self)
代码似乎工作得很好。但是,如果我删除 self.ping(),它将停止工作。套接字在浏览器端显示为打开,但是,永远不会调用服务器上的 on_message() 函数(Chrome 和 Firefox 中的行为相同)。为什么看起来服务器必须先在套接字上发送数据才能接收数据?
最佳答案
你的 python 是正确的,所以我猜错误是在你没有提供的客户端。确保在连接建立之前不要调用 send()。
这是一个完整的工作示例:
import tornado.websocket
import tornado.autoreload
import tornado.web
class LobbyWS(tornado.websocket.WebSocketHandler):
clients = []
def open(self, *args):
self.stream.set_nodelay(True)
LobbyWS.clients.append(self)
print 'opening %s' % self
def on_pong(self, data):
print 'got pong', data
def on_message(self, message):
print "Client %s received a message : %s" % (self, message)
for client in LobbyWS.clients:
client.write_message(message)
def on_close(self):
print "Client %s closed." % self
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("""
<html><head><script>
console.log('starting ws connection');
var connection = new WebSocket('ws://127.0.0.1:8888/lobby');
connection.onopen = function () {
console.log('open');
connection.send('Hello Server');
};
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
</script></head></html>
""")
application = tornado.web.Application([
(r"/", MainHandler),
(r"/lobby", LobbyWS),
])
if __name__ == "__main__":
application.listen(8888)
tornado.autoreload.start()
tornado.ioloop.IOLoop.instance().start()
希望这对您有所帮助。
关于python - Tornado Websockets 在没有 ping 的情况下不会调用 on_message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21584886/