Send message to multiple clients over websocket

2,717 views
Skip to first unread message

mishudark

unread,
Nov 28, 2010, 3:17:29 PM11/28/10
to Tornado Web Server
In the api, I can't see any method to send a message to various
clients connected over websocket, or how can I send a message to a
especific users over websocket at the same time?

Gavin M. Roy

unread,
Nov 28, 2010, 4:08:42 PM11/28/10
to python-...@googlegroups.com
Each instance of a Websocket class holds only the one connection to
that one user. If you want to say, build a chat room, you keep a list
of each websocket object handle and iterate over the list, sending to
each client.

mishu dark

unread,
Nov 28, 2010, 4:52:05 PM11/28/10
to python-...@googlegroups.com
And how can I get the list of the websocket conections?

2010/11/28 Gavin M. Roy <g...@myyearbook.com>

Sean Brant

unread,
Nov 28, 2010, 5:01:18 PM11/28/10
to python-...@googlegroups.com, python-...@googlegroups.com
Inside the on connect handler you would add the client to a global list.

clients = []

def on_connect_handler(self, ...):
    clients.append(self)

def on_message_handler(self, ...):
    for client in clients:
         client.send(...)

Something like that.

Gavin M. Roy

unread,
Nov 28, 2010, 5:04:36 PM11/28/10
to python-...@googlegroups.com
Was going to add this but accidentally sent before I could add it.

def on_message(self, message):

for websocket in websockets:
if websocket != self:
websocket.send(message)


On Sun, Nov 28, 2010 at 5:02 PM, Gavin M. Roy <g...@myyearbook.com> wrote:
> You need to maintain your own list.  There may be a better way but in
> my file that I have my Websocket class, I do something like:
>
> Note this is from memory and not double checked for accuracy in names, etc.
>
> import tornado.websocket
>
> websockets = []
>
> class MyWebsocket(tornado.websocket.Websocket):
>
>    def open(self):
>        if self not in websockets:
>            websockets.append(self)
>
>
>
>    def on_close(self):
>       offset = 0
>       for websocket in websockets:
>           if websocket == self:
>               break
>           offset += 1
>       websockets.pop(offset)

mishu dark

unread,
Nov 28, 2010, 7:39:27 PM11/28/10
to python-...@googlegroups.com
ok, thank's for the example
Reply all
Reply to author
Forward
0 new messages