Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tornado send message to all connections

Tags:

python

tornado

I have this simple code for a websocket server:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import time

class WSHandler(tornado.websocket.WebSocketHandler):

  def open(self):
    print 'New connection was opened'
    self.write_message("Conn!")

  def on_message(self, message):
    print 'Got :', message
    self.write_message("Received: " + message)


  def on_close(self):
    print 'Conn closed...'


application = tornado.web.Application([
  (r'/ws', WSHandler),
])

if __name__ == "__main__":
  http_server = tornado.httpserver.HTTPServer(application)
  http_server.listen(65)
  tornado.ioloop.IOLoop.instance().start()

I want to be able to send a message to all connected clients, but i don't know, and i don't seem to find that anywhere. A little help please? Thanks

like image 319
gogu Avatar asked Aug 30 '13 11:08

gogu


1 Answers

At the first your should start to manage incoming connections manualy, that's cause tornado don't do that from the box. As naive implementation you could do like this:

class WSHandler(tornado.websocket.WebSocketHandler):
  connections = set()

  def open(self):
     self.connections.add(self)
     print 'New connection was opened'
     self.write_message("Conn!")

  def on_message(self, message):
     print 'Got :', message
     self.write_message("Received: " + message)


  def on_close(self):
     self.connections.remove(self)
     print 'Conn closed...'

so if you need same message to all connections you can do that:

 [con.write_message('Hi!') for con in connections]
like image 64
Denis Avatar answered Oct 07 '22 01:10

Denis