使用Flask-socketIO进行即时消息传递 [英] Instant messaging with Flask-socketIO
问题描述
我想使用Flask + Flask-soketIO实现即时消息服务器.客户端在手机上(Ionic 2的正面)
我已经用socketIO尝试了不同的聊天室示例,但是我想知道如何管理多个用户两个两个地聊天.
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 :
- 首先,Flask是一个为手机应用程序实现即时消息传递的好框架吗?
我确实从Flask开始,因为它看上去功能强大且不像Django那样笨重. - 在具有sokcetIO的即时消息应用程序中,如何将用户两两相连?
我尝试了这段代码,但是它可用于同一聊天室中的多个用户:
在客户端:
<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)
- 它具有可扩展性,并且支持繁忙的流量吗?
推荐答案
在具有sokcetIO的即时消息应用程序中,如何将用户两两相连?
In instant messaging app with sokcetIO, how can I connect users two by two?
如果总是两个用户聊天,那么他们可以彼此直接发送消息.客户端连接时,将为其分配一个会话ID,即 sid
.如果您跟踪这些ID并将其映射到您的用户,则可以向特定用户发送消息.例如,如果将用户的 sid
值存储在用户数据库中,则可以按照以下方式向该用户发送直接消息:
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 ?
有许多因素会影响服务器可以处理的流量.Flask-SocketIO服务器具有可伸缩性,从某种意义上说,如果单个进程无法处理流量,则可以添加更多进程,基本上为您提供了很大的增长空间.
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.
这篇关于使用Flask-socketIO进行即时消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!