1、客户端向服务端推数据
WSGIServer默认处理的是http请求,路由视图中可以正常使用http,但是在使用ws协议时务必在视图函数通过request.environ.get('wsgi.websocket')获取与客户端的ws连接websocket_obj ,通过连接websocket_obj 进行websocket_obj .recive()/websocket_obj .send()通信,这个方法会对字符串自动进行编解码。
server端代码
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(str(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()
浏览器提供了websocket客户端,直接new创建websocket连接ws,通过ws.onmessage=function (MessageEvent){}监听执行回调函数获取信息MessageEvent.data,通过ws.send()发送信息
client端代码
<!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.onopen=function () {
const arr = [1, 2, 3,4,5,6,7,8,9];
for(let i = 0; i< arr.length; i++)
{
ws.send(arr[i]);
}
}
//接收数据
ws.onmessage = function (messageEvent) {
console.log(messageEvent.data)
}
</script>
</body>
</html>
运行结果图
2、服务端向客户端推数据
client端代码
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["wsgi.websocket"] # type:WebSocket
user_msg = user_socket.receive()
if user_msg=="1":
print("接收到数据啦")
for i in range(1000):
user_socket.send(str(i)+'yoyo')
print("数据发送完毕")
return "OK"
if __name__ == '__main__':
# app.run()
#在APP外封装websocket
http_serv = WSGIServer(("0.0.0.0",5000),app,handler_class=WebSocketHandler)
# 启动服务
http_serv.serve_forever()
server端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket客户端</title>
</head>
<body>
<input type="text" id="idname">
<script type="application/javascript">
// 客户端接收数据
var ws = new WebSocket("ws://127.0.0.1:5000/conn");
console.log(ws);
ws.onopen = function () {
alert("websocket is 就绪");
ws.send("1")
console.log(ws);
};
ws.onmessage = function (ws_status) {
document.getElementById("idname").value=ws_status.data;
console.log(ws_status.data)
};
</script>
</body>
</html>
运行结果图
参考链接:python flask框架上增加websocket的功能 --> fearlazy
flask之gevent-websocket的IO多路复用长连接通信 - 笑得好美 - 博客园