Flask 安装 Flask-Socketio
Flask-SocketIO 第三方库使 Flask 应用程序可以实现客户端和服务器之间的低延迟双向通信。客户端应用程序可以使用 Javascript、Python、C++、Java 和 Swift 中的任何 SocketIO 客户端库或任何其他兼容客户端来建立与服务器的永久连接。
Flask-Socketio 官方文档网站
网站地址:https://flask-socketio.readthedocs.io/en/latest/
初始化源码
from flask import Flask, request
from flask_socketio import SocketIO
app = Flask(__name__)
from flask_cors import *
CORS(app, supports_credentials=True)
app.config['SECRET_KEY'] = 'EDGEHACKER520!'
socketio = SocketIO(app, cors_allowed_origins='*')
name_space = '/echo'
@socketio.on('connect', namespace=name_space)
def champion_connect():
print(request)
return True
@socketio.on('disconnect', namespace=name_space)
def champion_disconnect():
pass
if __name__ == '__main__':
print("启动成功")
socketio.run(app, host='0.0.0.0', port=3000, debug=False)
常见报错:[2024-03-23 17:15:53,830] WARNING in __init__
: WebSocket transport not available. Install gevent-websocket for improved performance.
报错解决方案
pip install gevent-websocket
前端 socket.io-client 客户端
npm install socket.io-client
客户端连接案例源码
import io from 'socket.io-client';
export default {
data() {
return {
socket: null
};
},
mounted() {
this.socket = io.connect('ws://localhost:3000/echo?uid=helloworld', {
timeout: 300000, reconnectionDelayMax: 1000, reconnectionDelay: 500
})
}
}
服务器端读取连接请求
@socketio.on('connect', namespace=champion_space)
def champion_connect():
print(request.args)
return True
ImmutableMultiDict([('uid', 'helloworld'), ('EIO', '4'), ('transport', 'polling'), ('t', 'OvhXJvg')])