
前端用的 vue,后端用的 flask,有个路由需要使用 websocket 通信,现在是可以通信了,但后端怎么把数据实时的推给前端呢?后端在后面一直 while 循环推送的话,则访问其它的路由会失败,如果后端开多线程的话,会报 socket 死亡的问题,无法通信.
python:
from flask_sockets import Sockets @sockets.route('/msg') def echo_socket(ws): response_data = {'code': '', 'message': '', 'data': '', 'total': ''} try: if request.method == 'GET': user_socker = request.environ.get('wsgi.websocket') request_data = json.loads(user_socker.receive()) t1 = threading.Thread(target = check_status, args=(request_data, user_socker,), daemon = True) t1.start() 报错信息: user_socker.send(json.dumps(response_data)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/geventwebsocket/websocket.py", line 347, in send raise WebSocketError(MSG_SOCKET_DEAD) geventwebsocket.exceptions.WebSocketError: Socket is dead
vue:
initWebSocket() { //初始化 weosocket const wsuri = 'ws://127.0.0.1:8800/msg' //ws 地址 this.websock = new WebSocket(wsuri) this.websock.Onopen= this.websocketonopen this.websock.Onmessage= this.websocketonmessage this.websock.Onerror= this.websocketonerror this.websock.Onclose= this.websocketclose },
1 Latin 2020-12-24 12:05:23 +08:00 sockets 的异步需要 eventlet 和 gevent 的加持 另外不建议 flask 使用 sockets 换个思路 socketio 更适合 flask |
2 Latin 2020-12-24 12:05:42 +08:00 flask-socketio |
| td width="auto" valign="top" align="left"> |
5 wzwwzw 2020-12-25 00:00:22 +08:00 flask-socketio 应该是最优的选择了,只不过在部署的时候会麻烦一些。 |