码迷,mamicode.com
首页 > Web开发 > 详细

Flask+gevent-websocket模块实现websocket

时间:2019-08-20 20:33:56      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:接收   lang   rom   out   asc   sage   data   提示   cat   

后端代码:

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

标签:接收   lang   rom   out   asc   sage   data   提示   cat   

原文地址:https://www.cnblogs.com/jayxuan/p/11385240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!