Tornado websites do not call on_message without ping

It infuriates me. I am using Tornado 3.2 with python 2.7. I tried this both on my test computer (Windows) and on my Linux box. I am just testing the waters with (as I thought) a dead simple chat application. Here is the code so far:

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)

The code seems to be working fine. However, if I remove self.ping (), it will stop working. The socket opens at the end of the browser, however, the on_message () function on the server is never called (the same behavior in Chrome and Firefox). Why does it seem that the server should send data to the socket before it can receive it?

+3
source share
1 answer

, , , . 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()

, .

+1

All Articles