Reputation: 11
I am trying to build a flask app in which users can chat in group as well as each other. in order to implement this i am using flaskSocketio. I am able to broadcast my message but how can i do one to one chat....between different users I have database of users registered to me.......
@app.route("/chat/")
def chatting():
return render_template('chatHome.html')
@socketio.on('message')
def handleMessage(msg):
send(msg, broadcast=True, include_self=False)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=(int)(os.environ.get('PORT', 7001)),
debug=True)
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect();
socket.on('message', function(msg) {
$("#messages").append('<p style="padding: 10px; background-color: hotpink;
overflow: auto;">'+msg+'</p>');
console.log('Received message');
});
$('#sendbutton').on('click', function() {
socket.send($('#myMessage').val());
$("#rightsend").append('<p style="padding: 10px; background-color:
#2aabd2; overflow: auto;">'+($('#myMessage').val())+'</p>');
$('#myMessage').val('');
});
$("#myMessage").keyup(function(event){
if(event.keyCode == 13){
$("#sendbutton").click();
}
});
});
</script>
Upvotes: 1
Views: 1299
Reputation: 67489
Each user gets assigned a session ID or sid
when they connect. You can access the sid
assigned to a client as request.sid
in any event handler for that client. What people typically do is associate the sid
given to a client to the actual user in the connect event handler.
Once you have a way to find the sid
currently associated with a user, the server can send a message just to that user by adding a room=sid
argument to the emit()
call.
Upvotes: 2