Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

389
Vistas
Flask-socketio, send message only to one chat

I am developing flask app with chat feature. When somenone sends message, it saves into db. Now I want to display it on screen with socketio but when someone sends message, it shows in every currently used chat. Does anyone know how to display message only in one correct chat? Every two users have own chat with ID or can create it by sending message.

main.py code:

 @app.route('/chat/<int:id>', methods=['GET', 'POST'])
    @login_required
    def chat(id):
        chat = Chats.query.get_or_404(id)
        form = MessageForm()
        messages = chat.messages
        chat_id = chat.id
        if current_user.id == chat.first_user or current_user.id == chat.second_user:
            if request.method == "POST":
                form1 = request.form.get("myMessage")
                chat_id = chat.id
                author = current_user.id
                message = Messages(author=author, chat=chat_id, content=form1)
                chat.last_message = datetime.utcnow()
                db.session.add(message)
                db.session.commit()
            return render_template('chat.html', chat=chat, messages=messages, form=form, chat_id = chat_id)
        else:
            return redirect(url_for('index'))


@socketio.on('message')
def handleMessage(msg):
    print('Message: ' + msg)
    send(msg, broadcast=True)

chat.html code:

<script type="text/javascript">
    $(document).ready(function() {
    
        var socket = io.connect('http://127.0.0.1:5000');
    
        socket.on('connect', function() {
            socket.send('User has connected!');
        });
    
        socket.on('message', function(msg) {
            $("#messages").append('<li>'+msg+'</li>');
            console.log('Received message');
        });
    
        $('#sendbutton').on('click', function() {
            socket.send($('#myMessage').val());
            $('#myMessage').val('');
        });
    
    });
    </script>
    <ul id="messages"></ul>
    <input type="text" id="myMessage">
    <button id="sendbutton">Send</button>
  
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I was just struggling with this issue. Using the 'to' argument in emit() worked for me. This also works for the send() function. https://flask-socketio.readthedocs.io/en/latest/getting_started.html#:~:text=For%20many%20applications,the%20to%20argument.

Update

For added clarity, use Flask-SocketIO's rooms and use "to" argument (see documentation). Assuming that chat_id is the room, try:

chat.html

<script type="text/javascript">
    $(document).ready(function() {
    
        var socket = io.connect('http://127.0.0.1:5000');
    
        socket.on('connect', function() {
            socket.send('join_room', {
                name: "{{ user }}",
                room: "{{ chat_id }}"
            })
        });
    
        socket.on('receive_message', function(data) {
            $("#messages").append('<li>'+data.msg+'</li>');
            console.log('Received message');
        });
    
        $('#sendbutton').on('click', function() {
            var msg = $('#myMessage').val();
            socket.send('send_message', {
                msg: msg,
                room: "{{ chat_id }}"
            })
            $('#myMessage').val('');
        });

        window.onbeforeunload = function(data) {
        socket.emit('leave_room', {
            name: "{{ user }}",
            room: "{{ chat_id }}"
        })
    };
    
    });
    </script>
    <ul id="messages"></ul>
    <input type="text" id="myMessage">
    <button id="sendbutton">Send</button>

main.py

@app.route('/chat/<int:id>', methods=['GET', 'POST'])
    @login_required
    def chat(id):
        chat = Chats.query.get_or_404(id)
        form = MessageForm()
        messages = chat.messages
        chat_id = chat.id
        user = current_user.id
        if current_user.id == chat.first_user or current_user.id == chat.second_user:
            if request.method == "POST":
                form1 = request.form.get("myMessage")
                chat_id = chat.id
                author = current_user.id
                message = Messages(author=author, chat=chat_id, content=form1)
                chat.last_message = datetime.utcnow()
                db.session.add(message)
                db.session.commit()
            return render_template('chat.html', chat=chat, messages=messages, form=form, chat_id = chat_id, user=user)
        else:
            return redirect(url_for('index'))

@socketio.on('join_room')
def handle_join_room_event(data):
    name = data['name']
    room = data['room']
    join_room(room)
    socketio.send(name + 'has connected!', to=room)

@socketio.on('send_message')
def sendMessage(data):
    room = data['room']
    send('receive_message', data, to=room)

@socketio.on('leave_room')
def handle_join_room_event(data):
    name = data['name']
    room = data['room']
    leave_room(room)
    socketio.send(name + 'has disconnected', to=room)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda