Flask+gevent-websocket模块实现websocket
Posted jayxuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask+gevent-websocket模块实现websocket相关的知识,希望对你有一定的参考价值。
后端代码:
from flask import Flask,request from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket #这条做语法提示用 app = Flask(__name__) @app.route(‘/conn‘) def index(): #获取请求原始数据 user_socket = request.environ #获取websocket对象 websocket_obj = user_socket[‘wsgi.websocket‘] #type:WebSocket while True: #循环监听 # 监听链接,接收数据 msg = websocket_obj.receive() print(msg) websocket_obj.send(msg+‘youtoo‘) if __name__ == ‘__main__‘: # app.run() #在APP外封装websocket http_serv = WSGIServer(("0.0.0.0",5000),app,handler_class=WebSocketHandler) # 启动服务 http_serv.serve_forever()
模板代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket客户端</title> </head> <body> <script type="application/javascript"> var ws = new WebSocket(‘ws://127.0.0.1:5000/conn‘); //建立websocket链接 //接收数据 ws.onmessage = function (messageEvent) console.log(messageEvent.data) </script> </body> </html>
以上是关于Flask+gevent-websocket模块实现websocket的主要内容,如果未能解决你的问题,请参考以下文章
python-flask复习——- flask请求上下文源码解读http聊天室单聊/群聊(基于gevent-websocket)
WebSocket 传输不可用。安装 eventlet 或 gevent 和 gevent-websocket 以提高性能