0

Here is my back-end:

    from flask import Flask, render_template
    from flask_socketio import SocketIO, send, 
    emit

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    socketio = SocketIO(app)

    @app.route('/chat')
    def chat():
        return render_template('chat.html')

    @socketio.on('greet')
    def reply(data):
        emit('reply', data, namespace='/chat')    

And here is my front:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
    <script>
    var socket = 
    io.connect('http://127.0.0.1:5000/');
    var socketChat = 
    io.connect('http://127.0.0.1:5000/chat');
    socket.on('connect', function() {
        let greeting = "hey"
        socket.emit('greet', greeting)
    });

    // The function that does not work as expected
    socketChat.on('reply', namespace='/chat', 
    function(msg) {
        console.log('hello');
        console.log(msg);
    })
    </script>  

I basically do as the doc told me:

    @socketio.on('my event')
    def handle_my_custom_event(json):
        emit('my response', json, 
    namespace='/chat')

but have no idea why the front doesn't receive that.

Please help me out to let the front receive the event!

Cody Gao
  • 3
  • 3
  • Why are you using two different sockets? Your server is going to respond on the socket that received the "greet". – Tim Roberts Jul 09 '23 at 03:57
  • Another socket there is for listening to the events from 'http://127.0.0.1:5000/chat', which is namespace called '/chat', so they can work together. That's what I think about the 'namespace' in socketIO. Please correct me if I am wrong. – Cody Gao Jul 09 '23 at 05:10
  • You need to have at least one handler for the other namespace in order for flask to manage it. Note that namespaces are not typically used in socketio. – Tim Roberts Jul 09 '23 at 05:49

0 Answers0