flask socketio:1

崔琦
2023-12-01

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:

  • 后端基于flasksocketio,前端的socketio只要遵循协议即可。不过前端一般使用js的。

1. Initialization

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)

2. 事件

socketio支持用户自定义事件,注意 message、json、connect、disconnect为保留事件。

1.接收消息

1.几类事件

  • connect事件:
# @socketio.on("connect", namespace="/test")
@socketio.on("connect")
def test_connect():
    print("client connect success!")
  • disconnect事件:
# @socketio.on("disconnect", namespace="/test")
@socketio.on("disconnect")
def test_disconnect():
    print("client disconnect!")
  • message事件:
@socketio.on('message')
def handle_message(message):
    print("received message: " + message)
  • json事件:
@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);
            });

2.命名空间

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

2.发送消息

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:

  • send发送的消息,前端(本笔记前端是js写的)接收的事件是‘message’
  • emit抛出一个事件,对应的前端事件就是emit第一个参数所标记的事件

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

3.广播

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

 

 类似资料: