美文网首页
通过flask-socketio实现websocket通讯

通过flask-socketio实现websocket通讯

作者: 忘了呼吸的那只猫 | 来源:发表于2021-12-30 16:51 被阅读0次

首先是安装flask-socketio库

pip install flask-socketio

注意:flask-socketio存在兼容问题,使用的时候可能会出现下面这种错误

The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO)

解决方法:安装低版本和对应的依赖
我安装的以下版本

Flask-SocketIO==4.3.1
python-engineio==3.13.2
python-socketio==4.6.0

如果已经安装了最新版本可以用以下的方式解决

pip install --upgrade python-socketio==4.6.0

pip install --upgrade python-engineio==3.13.2

pip install --upgrade Flask-SocketIO==4.3.1

测试代码:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.0/jquery.js"></script>
    <script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>
</head>
<body>
    <form id="emit">
        <label>my response:</label><input type="text" id="emit_data" value="test_submit"/> 
        <input type="submit" value="发送"/> 
    </form>
    <div id="log" style="width: 300px;height: 500px;background-color: #0C0C0C;
    color: white;text-align: center;line-height: 50px;margin-left: 40%;font-size: 20px"></div>

    <form id="emit2">
        <label>my broadcast event:</label><input type="text" id="emit_data2" value="test_submit"/> 
        <input type="submit" value="发送"/> 
    </form>
    <div id="log2" style="width: 300px;height: 500px;background-color: #0C0C0C;
    color: white;text-align: center;line-height: 50px;margin-left: 40%;font-size: 20px"></div>
    
 
    <script type="text/javascript" charset="utf-8">
        
        $(document).ready(function(){
            var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
            socket.on('my response', function(msg) {
                    $('#log').append('<p>my response: ' + msg.data + '</p>');
                });

            $('#emit').submit(function(event) {
                socket.emit('my event', {data: $('#emit_data').val()});
                return false;
            });
            
            socket.on('my broadcast event', function(msg) {
                    $('#log2').append('<p>my broadcast event: ' + msg.data + '</p>');
                });
            
            $('#emit2').submit(function(event) {
                socket.emit('my broadcast event', {data: $('#emit_data2').val()});
                return false;
            });
        });
    </script>
    </body>
</html>
'''


@app.route('/')
def index():
    return html

@socketio.on('my event', namespace='/test')
def test_message(message):
    print('接收到客户端数据:',message)
    emit('my response', {'data': message['data']})

@socketio.on('my broadcast event', namespace='/test')
def test_message(message):
    print('my broadcast event',message)
    emit('my broadcast event', {'data': message['data']}, broadcast=True) # broadcast参数为true可以广播到所有连接到my broadcast event的用户

@socketio.on('connect', namespace='/test')
def test_connect():
    print('websocket已连接')
    emit('my response', {'data': 'hello boy'})

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('对方已断开连接')

if __name__ == '__main__':
    socketio.run(app)

直接运行这段代码,测试连接和通讯是否正常

相关文章

网友评论

      本文标题:通过flask-socketio实现websocket通讯

      本文链接:https://www.haomeiwen.com/subject/eloiqrtx.html