Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tornado send message on event

Im creating a program in Python that reads a stream of data on an unknown interval. This program also sends this data through websockets. The program is the server and it sends the received data to the clients.

This is the code of the server now:

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def initialize(self):
        print 'Websocket opened'

    def open(self):
        print 'New connection'
        self.write_message('Test from server')

    def on_close(self):
        print 'Connection closed'

    def test(self):
        self.write_message("scheduled!")

def make_app():
    return tornado.web.Application([
    (r'/ws', WebSocketHandler),
    ])

if __name__ == '__main__':
    application = make_app()

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

But I want to be able to use write_message in this loop:

def read_function():
    while True:
        time.sleep(10) # a while loop to simulate the reading
        print 'read serial'
        str = 'string to send'
        # send message here to the clients

How am I supposed to do this?

EDIT: will there be a problem with both threads using connections? It seems like it works with 1 connection.

def read_function():
    while True:
        time.sleep(5) # a while loop to simulate the reading
        print 'read serial'
        str = 'string to send'
        [client.write_message(str) for client in connections]

if __name__ == '__main__':
    thread = Thread(target = read_function)
    application = make_app()
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    thread.start()
    tornado.ioloop.IOLoop.instance().start()
    thread.join()
like image 912
J. Daniel Avatar asked Mar 13 '26 11:03

J. Daniel


1 Answers

Use connections = set() outside the WebsocketHandler and add every client on opening a connection with connections.add(self). Do not forget to remove them on closing with connections.remove(self).

Now, you are able to access write_message out of the websocket thread through: [client.write_message('#your_message') for client in connections]

like image 121
Kjub Avatar answered Mar 16 '26 00:03

Kjub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!