1

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:

  • I dove in to the gevent-socketio code and see that the sockets are kept tracked there. But I am not sure what would be the next step.
  • Noticed that, in Flask, request.environ has a socketio value that corresponds to the object. However, that's only on SocketIO requests.

Any clues or hints would be very appreciated.

Belmin Fernandez
  • 8,307
  • 9
  • 51
  • 75

1 Answers1

0

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.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • My problem is getting the `server` object in a non-SocketIO request. I did some ugly hack to do this now using `global` but there has to be a better way. Will post runnable code soon to better explain my issue. Appreciate your input and time of course! – Belmin Fernandez Feb 27 '15 at 13:14
  • add your socketio server to your Flask app instance (i.e. `app.socketio = server`), then reference it as `current_app.socketio`. – Miguel Grinberg Feb 27 '15 at 15:27