问题
I want to implement an instant messaging server using Flask + Flask-soketIO.
with client side on mobile phone (front in Ionic 2)
I have already tried different chat room examples with socketIO but I wonder how to manage multiple users chatting two by two.
I'm not yet familiar with instant messaging architectures. I have several questions on the subject :
- first of all, is Flask a good framework to implement instant messaging for mobile phone application ?
I did start with Flask because it seems powerful and not heavy as django can be. - In instant messaging app with sokcetIO, how can I connect users two by two?
I tried this code, but it works for multiple users in the same tchat room :
On the client side :
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect("http://127.0.0.1:5000");
socket.on('connect', function() {
console.log('connected')
});
socket.on('message',function(msg){
$("#messages").append('<li>' + msg + '</li>');
});
$("#sendButton").on('click', function() {
console.log($('#myMessage').val());
socket.send({ 'author': 'Kidz55',
'message': $('#myMessage').val()});
$('#myMessage').val('');
});
});
</script>
On the server side :
@socketio.on('message')
def handle_json(json):
print('received json: ' + str(json))
# broadcasting to everyone who 's connected
send(json,,broadcast=True)
- Is it scalable, and does it support heavy traffic ?
回答1:
In instant messaging app with sokcetIO, how can I connect users two by two?
If it is always going to be two users chatting, then they can send direct messages to each other. When a client connects, it gets assigned a session id, or sid
. If you keep track of these ids and map them to your users, you can then send a message to specific users. For example, if you store the sid
value for a user in your user database, you can then send a direct message to that user as follows:
emit('private_message', {'msg': 'hello!'}, room=user.sid)
Is it scalable, and does it support heavy traffic ?
There are many factors that influence how much traffic your server can handle. The Flask-SocketIO server is scalable, in the sense that if a single process cannot handle the traffic, you can add more processes, basically giving you a lot of room to grow.
来源:https://stackoverflow.com/questions/44517248/instant-messaging-with-flask-socketio