python 使用flask-socketio

安装flask-socketio

pip install flask-socketio

服务端

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

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

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

name_space = '/dcenter'

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

@app.route('/push')
def push_once():
    event_name = 'dcenter'
    broadcasted_data = {'data': "test message!"}
    # 服务端发送给前端事件消息
    socketio.emit(event_name, broadcasted_data, broadcast=False, namespace=name_space)
    return 'done!'

@socketio.on('connect', namespace=name_space)
def connected_msg():
    print('client connected.')

@socketio.on('disconnect', namespace=name_space)
def disconnect_msg():
    print('client disconnected.')

# 后端接收事件消息
@socketio.on('my_event', namespace=name_space)
def mtest_message(message):
	# 不同的事件
    print(message)
    emit('my_response',
         {'data': message['data'], 'count': 1})

if __name__ == '__main__':

    socketio.run(app, host='0.0.0.0', port=5000, debug=True)

前端

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SocketIO Demotitle>
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js">script>
    <script type="text/javascript" src="//cdn.socket.io/4.4.1/socket.io.js">script>
head>
<body>

<h2>Demo of SocketIOh2>
<div id="t">div>
<script>
$(document).ready(function () {
    namespace = '/dcenter';
    var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
    // 前端发送消息
    socket.emit('my_event',{'data':'hello world'});
    // 前端接收消息
    socket.on('dcenter', function (res) {
        var t = res.data;
        if (t) {
            $("#t").append(t).append('
'
); } }); socket.on('my_response', function (res) { var t = res.data; if (t) { $("#t").append(t).append('

'
); } }) });
script> body> html>

这里需要注意的是,当前我使用的flask-socketio版本是5.2,需要对应前端socket.io版本是4.x,否则会报错。

你可能感兴趣的:(python,flask,python,前端)