一个简单的flask-socket服务端示例

2021-06-15 11:38:25 浏览数 (1)

代码语言:javascript复制
from flask import Flask, render_template,request
from flask_socketio import SocketIO
from flask_socketio import send, emit

<!--more-->

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

# 解决flaks_socketio 的跨域问题
socketio = SocketIO(app,cors_allowed_origins='*')

@app.route('/push/',methods=['POST'])
def post_Data(): # 这个是请求这个网址后,服务器主动向客户端发送ws消息
    msg = request.form
    msg = dict(msg)

    # 但对于某些情况,服务端需要作为消息的发起者。比如服务器需要在后端向所有客户端发送通知的情景中,
    # socketio.send()和socketio.emit()可以用来向所有用户发送广播
    socketio.emit('server',{'msg': msg,'statu':'2'} , broadcast=True,json=True)
        
    return 'done!'


@socketio.on('client')
def test_client(msg):
    print(msg)
    emit('server', {'data': 'client'} ) # , broadcast=True)

@socketio.on('connect')
def test_connect():
    print('Client connect')
    emit('server', {'data': 'hi~'})

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')

@socketio.on('json')
def handle_json(json):
    send(json, json=True,broadcast=True)


if __name__ == '__main__':
    print('run')
    socketio.run(app,host='0.0.0.0',port=5000)

0 人点赞