Belmin Fernandez
Belmin Fernandez

Reputation: 8647

How do I broadcast from a non-SocketIO request to all SocketiO clients connected?

I'm running the SocketIO server with something like:

from socketio.server import SocketIOServer
server = SocketIOServer(
   ('127.0.0.1', '8000'),
   resource='socket.io',
)
server.serve_forever()

I then have a namespace:

class Foo(BaseNamespace, BroadcastMixin):
    def on_msg(self, data):
        self.emit(data['msg'])

And finally, I have a route such as:

module = Blueprint('web', __name__)
@module.route('/')
def index():
    pkt = dict(
              type='event',
              name='new_visitor',
              endpoint='/foo'
           )

    ## HERE: How do I get the "socket" to look through each connection
    #for sessid, socket in blah.socket.server.sockets.iteritems():
    #    socket.send_packet(pkt)

    return render_template('index.html')

So, the above commented part is where I have issue.

What I've done so far:

Any clues or hints would be very appreciated.

Upvotes: 1

Views: 287

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67492

The code that I use on my Flask-SocketIO extension to do what you want is:

def emit(self, event, *args, **kwargs):
    ns_name = kwargs.pop('namespace', '')
    for sessid, socket in self.server.sockets.items():
        if socket.active_ns.get(ns_name):
            socket[ns_name].emit(event, *args, **kwargs)

My actual implementation is a bit more complex, I have simplified it to just show how to do what you asked. The extension is on github if you want to see the complete code.

Upvotes: 0

Related Questions