flask websocket

websocket使用自定义标识连接(服务端客户端使用相同标识)
通常发送和接收,使用两个不同信道,不然会触发无线循环

send #简单文本发送
emit #复杂数据发送

__init__.py:

#这里是初始化设置,包括创建app实例,注册蓝图,配置app,配置peewee
from flask import Flask
from config import Config
from .views import view
from .api import api
from .models import peeweeDB, DB, User
from .socketio import socketio

# 创建app实例
app = Flask(__name__)
app.config.from_object(Config) #配置app
app.register_blueprint(view) #注册视图蓝图
app.register_blueprint(api) #注册api蓝图

socketio.init_app(app) #注册socketio
# 将peewee集成到flask中
peeweeDB.init_app(app)

# 创建表
with app.app_context():
    DB.create_tables([User])

socketio.py:

# 避免互导,单独使用一个文件创建socket实列
from flask_socketio import SocketIO
socketio = SocketIO()

views.py:

#这是一个视图蓝图模块,不需要引入app,将直接在app/__init__.py中引入
from flask import Blueprint, render_template
# from .models import User, DB
from .task import huey,sendcode
from flask_socketio import send, emit
from .socketio import socketio

view = Blueprint('view', __name__)

@view.route('/')
def index():

    huey.enqueue(sendcode.s(priority=10))
    return render_template('index.html',text='欢迎来到首页')

# 监听客户端message事件,这是一个约定俗成的事件,如果客户端未指定事件名则默认向它发送
@socketio.on('message')
def handle_message(message):
    print('received message: ' + message)
    send(message, broadcast=True)

# 监听客户端custom_event事件,然后使用response事件返回数据
@socketio.on('custom_event')
def handle_custom_event(json):
    print('received json: ' + str(json))
    emit('response', {'data': '服务端返回的数据'})

index.html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
    <script type="text/javascript" charset="utf-8">
        document.addEventListener("DOMContentLoaded", function() {
            var socket = io();
                // 监听内置连接事件
            socket.on('connect', function(msg) {
                socket.send('客户端连接成功');
            });
            // 监听服务端message事件(自定义)
            socket.on('message', function(msg) {
                var p = document.createElement('p');
                p.innerHTML = msg;
                document.body.appendChild(p);
            });
                // 监听服务端response事件(自定义)
            socket.on('response', function(data) {
                var p = document.createElement('p');
                p.innerHTML = data.data;
                document.body.appendChild(p);
            });

            document.getElementById('sendButton').onclick = function() {
                var input = document.getElementById('messageInput').value;
                //默认向message事件发送数据
                socket.send(input);
            };

            document.getElementById('customButton').onclick = function() {
                socket.emit('custom_event', {data: '你好,我是客户端'});
            };
        });
    </script>
    <h1>{{ text }}</h1>
    <input id="messageInput" type="text" placeholder="Type a message...">
    <button id="sendButton">发送</button>
    <button id="customButton">发送自定义事件</button>