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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With