'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>
  


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source