WebSocket is already in CLOSING or CLOSED state解决方案

使用flask + websocket来进行前后端交互的项目

前端发送send的时候,websocket一连接就中断,测试了心跳设置相应时间等各种方法,都没用,最后发现原来是flask的版本太高导致和gevent不兼容

无论前端怎么发送信息,flask的服务器端什么都没有:

服务器端代码:

from geventwebsocket.handler import WebSocketHandler

from gevent.pywsgi import WSGIServer

from geventwebsocket.websocket import WebSocket # 引这个模块为了注释中显示提示用

from flask import Flask, render_template,request
app = Flask(__name__)

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

@app.route('/my_ws')
def my_ws():
    print(request.environ)
    user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
    while 1:
        msg = user_socket.receive()
        print(msg)
        user_socket.send(msg)

if __name__ == '__main__':
    # app.run()
    http_server = WSGIServer(('0.0.0.0',9527),app,handler_class=WebSocketHandler)
    http_server.serve_forever()

前端客户端代码:



我即将是Websocket



前端调试的时候老是报错:

WebSocket is already in CLOSING or CLOSED state解决方案_第1张图片

 最后将flask一系列的包都降级后,错误消失:

WebSocket is already in CLOSING or CLOSED state解决方案_第2张图片

解决流程: 

一开始的flask 的版本是2点多

Flask 降级

pip install Flask==1.1.2

ImportError: cannot import name 'escape' from 'jinja2

pip uninstall Jinja2

from flask) (1.1.0) Requirement already satisfied: Jinja2>=2.10.1

Pip install Jinja2==2.10.1

解决ImportError: cannot import name ‘soft_unicode‘ from ‘markupsafe‘

必须安装这个:pip install markupsafe==2.0.1

werkzeug 2.2.2 requires MarkupSafe>=2.1.1, but you have markupsafe 2.0.1 which is incompatible. 或者 ImportError: cannot import name 'json' from 'itsdangerous' (/Users/hyy/Desktop/项目/venv_37/lib/python3.7/site-packages/itsdangerous/__init__.py)

Pip install itsdangerous==2.0.1

ImportError: cannot import name 'BaseResponse' from 'werkzeug.wrappers' (/Users/hyy/Desktop/项目/venv_37/lib/python3.7/site-packages/werkzeug/wrappers/__init__.py)

Pip show werkzeug

Name: Werkzeug

Version: 2.2.2

继续降级:pip install werkzeug-1.0.1

你可能感兴趣的:(开发问题,websocket,flask,网络协议)