前端+后端python双向通信
目的
在前后端分离的基础上(不用flask的模板渲染),用后端的flaskio和前端的socketio实现双向通信。
代码
后端python代码,用的是3.7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
from flask import Flask from flask_cors import * from flask_socketio import SocketIO
app = Flask(__name__) CORS(app, supports_credentials=True) socketio = SocketIO() socketio.init_app(app, cors_allowed_origins='*')
name_space = '/dcenter'
@app.route('/') def index(): print() return "aasdlkfjasldkjf"
@socketio.on('my_event', namespace=name_space) def mtest_message(data): print(data) event_name = 'dcenter1' broadcasted_data = {"type": "delete", "user_id": "123", "data": "1111111111111"} socketio.emit(event_name, broadcasted_data, broadcast=False, namespace=name_space)
@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("message", namespace=name_space) def message(data): print("message")
if __name__ == '__main__': socketio.run(app, host='127.0.0.1', port=5000, debug=True)
|
前端代码
引入到了一个js库,在webstome里可以直接抓下载到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <title></title> </head>
<body> <h2>Demo of SocketIO</h2> <button id="btn1" type="button">点击发送信息</button> <br> <p id="t1">接收dcenter事件信息</p> <p id="t2"></p>
<script src="js/http_cdnjs.cloudflare.com_ajax_libs_socket.io_3.1.3_socket.io.js"></script> <script type="text/javascript"> function $(queryStr) { return document.querySelector(queryStr); }
window.onload = function () { let socket = io.connect(`http://127.0.0.1:5000/dcenter`); console.log(io); socket.on('dcenter1', function (res) { let t = JSON.stringify(res); if (t) { console.log("接收到了信息,", t) } });
socket.on('connect', function () { console.log('connect') }); socket.on('connect_error', (error) => { console.log("链接错误") }); socket.on('disconnect', (timeout) => { console.log('链接丢失') socket.close(); }); $("#btn1").addEventListener("click", function () { socket.emit('my_event', {'hello': "世界!"}); }); } </script> </body>
</html>
|
结尾:
参考博客然后修修改改终于成功运行
https://blog.csdn.net/qq_38463737/article/details/126678480
Author:
Littlefean
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE
Slogan:
仅个人观点,buddy up!