Flask-SocketIO gives Flask applications access to low latency bi-directional communications between the clients and the server. The client-side application can use any of the SocketIO official clients libraries in Javascript, C++, Java and Swift, or any compatible client to establish a permanent connection to the server.
ps:
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
if __name__ == '__main__':
socketio.run(app)
socketio支持用户自定义事件,注意 message、json、connect、disconnect为保留事件。
# @socketio.on("connect", namespace="/test")
@socketio.on("connect")
def test_connect():
print("client connect success!")
# @socketio.on("disconnect", namespace="/test")
@socketio.on("disconnect")
def test_disconnect():
print("client disconnect!")
@socketio.on('message')
def handle_message(message):
print("received message: " + message)
@socketio.on("json")
def handle_json(json):
print("received json: " + str(json))
@socketio.on("myevent")
def handle_my_custom_event(json):
print("received json: " + str(json))
@socketio.on("myevent2")
def handle_my_custom_event2(arg1, arg2, arg3):
print("received args: " + arg1 + arg2 + arg3)
@socketio.on("myevent3", namespace="/test")
def handle_my_custom_event3(json):
print("received json:" + str(json))
服务器端:
@socketio.on("myevent")
def handle_my_custom_event(msg):
print("received msg: " + msg)
return "ok"
浏览器端:
socket.emit("myevent", "hi myevent!", (msg)=>{
console.log(msg);
});
flask-socketio支持socketio的命名空间(命名空间我还不太懂)
命名空间的作用(引用官方):
namespace allows the client to multiplex several independent connections on the same physical socket
当不指定命名空间时,默认的命名空间是"/"。
写法1:
@socketio.on('my event', namespace='/test')
def handle_my_custom_namespace_event(json):
print('received json: ' + str(json))
写法2:
def my_function_handler(data):
pass
socketio.on_event('my event', my_function_handler, namespace='/test')
1.
from flask_socketio import send, emit
@socketio.on('message')
def handle_message(message):
send(message)
@socketio.on('json')
def handle_json(json):
send(json, json=True)
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json) # 触发前端事件"my response"
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', ('foo', 'bar', json), namespace='/chat') # 抛出的触发事件,同时有多个数据时,用数据结构tuple。
ps:
2.flask socketio支持回调来确认前端是否收到了数据: !
def ack():
print 'message was received!'
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json, callback=ack) # 实际测试中ack并未被调用。
3.支持命名空间
@socketio.on('message')
def handle_message(message):
send(message, namespace='/chat')
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json, namespace='/chat')
flask socketio支持广播,当设置broadcast=True时,所有连接的clients都会收到来自发送者的消息包括发送者自身。
When a message is sent with the broadcast option enabled, all clients connected to the namespace receive it, including the sender. When namespaces are not used, the clients connected to the global namespace receive the message. Note that callbacks are not invoked for broadcast messages.
@socketio.on('my event')
def handle_my_custom_event(data):
emit('my response', data, broadcast=True)
广播的使用案例就是当服务器想要主动给所有客户端发送数据时:
def some_function():
socketio.emit('some event', {'data': 42})