Flask-SocketIO: why the client can not receive the emit data during connecting?

@socketio.on("connect", namespace="/test")
def test_connect():
emit("my_response", {"data": "Connected", "count":0})

in the test demo, this works well, and i can see the data {“data”: “Connected”, “count”:0} in the webbrowser.

but if i use it like following:

@socketio.on("connect", namespace="/test")
def test_connect():
emit("my_response", {"data": "Connected", "count":0})
## add here ##
return False

then in the browser, it will try to connect, but the strange place is that i can not see the data {“data”: “Connected”, “count”:0} in the webbrowser console, i have used ipdb to trace, and it really has sent the data. so i am confused why client can not recieve the response data? can you help me? thanks

this is the pic without return False 企业微信截图_15591241442631

this is the pic with return False: 企业微信截图_15591240067634

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 16 (7 by maintainers)

Most upvoted comments

Okay, then this is wrong. You have two options to do that:

  1. Add the always_connect=True setting in the SocketIO constructor. This will fully accept the connection before the connect handler is invoked, so you can emit freely. If you return False, then a disconnect() will be issued to close the connection.

  2. Instead of returning False, raise a ConnectionRefusedError exception, which takes an argument where you can pass an error message back to the client:

from socketio import ConnectionRefusedError

@socketio.on('connect')
def connect():
    raise ConnectionRefusedError('authentication failed')