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