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>

 

posted @ 2019-08-20 20:01  adrrfsfsd  阅读(2589)  评论(0编辑  收藏  举报