emit() does not work sometimes #1950
-
Hi there, from flask import Flask
from flask_socketio import SocketIO, emit
socketio = SocketIO()
def _background():
while True:
print('cycle sync')
time.sleep(5)
socketio.emit(event='message', data={"msg": f"Bot:FOOOO!"})
def create_app() -> Flask:
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret'
# ...
socketio.init_app(
app=app,
path="/ws/socket.io",
cors_allowed_origins="*",
logger=True,
engineio_logger=True,
async_mode='gevent_uwsgi',
)
socketio.start_background_task(_background)
return app events.py: from flask import session
from flask_socketio import emit, join_room, leave_room
from .. import socketio
@socketio.on('joined', namespace='/chat')
def joined(message) -> None:
"""
Sent by clients when they enter a room.
A status message is broadcast to all people in the room.
"""
print(f'JOINED: {message}')
room = session.get('room')
join_room(room)
emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)
@socketio.on('text', namespace='/chat')
def text(message) -> None:
"""
Sent by a client when the user entered a new message.
The message is sent to all people in the room.
"""
room = session.get('room')
print('TEXT', room, message)
emit('message', {'msg': session.get('name') + ':' + message['msg']}, room=room)
@socketio.on('left', namespace='/chat')
def left(message) -> None:
"""
Sent by clients when they leave a room.
A status message is broadcast to all people in the room.
"""
room = session.get('room')
leave_room(room)
emit('status', {'msg': session.get('name') + ' has left the room.'}, room=room)
@socketio.on_error()
def on_error_default(message) -> None:
print(f'ON ERROR: {message}') run.py: from gevent import monkey
monkey.patch_all()
from websockets.app import create_app
app = create_app() DescriptionThe chat works completly fine, but the SockeIO events that are emitted from the background task are not received in the frontend. But the library debug logs of your library tell me, that those events were emitted correctly. Logs
Do you have an idea what's the issue here? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The emit is working fine, but you are using a different namespace. Try adding the correct namespace: socketio.emit(event='message', data={"msg": f"Bot:FOOOO!"}, namespace='/chat') |
Beta Was this translation helpful? Give feedback.
The emit is working fine, but you are using a different namespace. Try adding the correct namespace: