Search code examples
socket.ioflask-socketio

Flask-SocketIO Emit message and sent not working. (ValueDuplicationError)


I am using Flask-SocketIO(version: 5.0.1) in the backend and in the front end using socket.io (version 4.0.1). Backend code:

@socketio.on('connect')
def socket_connect():
    print(f"connected***** {request.args}")
    emit('my-response', {'data': 'Connected flask backend'}, room=f"room{request.sid}")

Here the print statement worked but emit is not working. After few seconds I get this error

bidict.ValueDuplicationError: ODpLc2T7oBppyH-VAAAX

Front end Js code:

socket.on("connect", function() {
    console.log("connn ");
})

when I checked the console the socket status looks like this:

connected: false
disconnected: true

In the Flask command if I removed the emit statement then in the console the socket connection status becomes like this:

connected: true
disconnected: false

Solution

  • Flask (Sever Side):

    from flask import Flask
    from flask import request
    from flask_socketio import send, SocketIO, emit, join_room
    
    app = Flask(__name__)
    
    socketio = SocketIO(app, cors_allowed_origins="*")
    
    @socketio.on('connect')
    def socket_connect():
        print(f"connected***** {request.args}")
        emit('my-response', {'data': 'Connected from flask'}, room=f"room{request.sid}")
    
    @socketio.on('join')
    def joined(data):
       print(f"***on_join*** {data}")
       join_room(room)
       send(f"{request.sid} has entered the room.", room=data['room'])
    
    @socketio.on("my-event")
    def client_event_response_trigger(json):
        print(request.args)
        print(request.json)
        socketio.emit("my-response", json)
    
    @socketio.on('disconnect')
    def socket_disconnect():
        print(f"Disconnected: {request.args}")
    
    

    Client-Side:

    socket_con_query
    var socket = io.connect("http://localhost:5000/", {query: "if needed then add the querystring"})
    
    socket.on("connect", function() {
        console.log("connecting")
        socket.emit("join", {room: "room"+socket.id, sid: socket.id})
        socket.emit("my-event", {"test": "tesing"})
    })
    
    socket.on('my-response', function(msg) {
        console.log("received: ", msg)
        socket.emit("my-event", {"test": "Demo"})
        })