Flask-socketio, emit an event to another namespace
Asked Answered
C

2

5

I am using Flask-socketio (http://flask-socketio.readthedocs.org/en/latest/).

I am currently getting a

KeyError: '/local'

when using this in events.py. Note the differing namespaces:

@socketio.on('connect', namespace='/photo')
def client_connect():
    emit('event', { 'type': 'client_connect' }, namespace='/local')

Using Flask-socketio is it possible to emit to a separate namespace to that which the event occurred on? The documentation seems to suggest so, but I can't workout why I keep getting the KeyError.

EDIT: Thanks @Miguel for your proposed answer, I have tried again (after a long time away from the project) but still get a keyerror with the below:

@socketio.on('connect', namespace='/local')
def local_client_connect():
    print ('Local client connected.')

@socketio.on('connect', namespace='/photo')
def client_connect():
    print ('Client connected.')
    send('client_connect', namespace='/local')

When I run the app I see the printed 'Local client connected.' and only then do I allow a client to access the /photo route. I see 'Client connected' printed and then of course the keyerror.

I have upgraded flask-socketio to 0.4.2.

Best

Andrew

Cajole answered 16/7, 2014 at 11:14 Comment(5)
did you find any solution, or figured out what to make in that case ? Thanks.Receive
I think I built the whole thing in node.js in the end! So I'm afraid not.Cajole
How did you implement it in nodejs socketio ?? did the example above worked ??Receive
It was a long time ago but using socket.io and I think emitting to the individual client. You can also put clients in a 'room' and broadcast to that room only. Check out the socket.io site, it has some great examples.Cajole
Why you've chosen back to nodejs? What are all the complexities you've faced here?Loftus
S
5

You need to have at least one handler on the second namespace. For example:

@socketio.on('connect', namespace='/local')
def local_client_connect():
    pass

Then Flask-SocketIO will know about /local and will be able to emit messages to it.

Supervene answered 16/7, 2014 at 17:5 Comment(1)
Hi @Miguel, I tried your suggestion but I am still getting a KeyError on 'local'. The handler for the second name space is declared before my original code and is also being called before it, ie. local_client_connect() happens before client_connect().Cajole
C
5

I had same problems and solved like this.

@socketio.on('connect', namespace='/photo')
def client_connect():
    socketio.emit('event', { 'type': 'client_connect' }, namespace='/local')
Carolus answered 3/6, 2019 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.