问题如标题,我用flask加websocket结合前端做了一个向前端实时推送数据的程序。但是我后续发现,前端的访问,同一时间只能支持一个访问。但是我需要能够在同一个时间能支持多个访问。一直没想出解决办法。特来请教。
后端部分:
from flask import Flask,render_template,request
from flask_sockets import Sockets
import datetime
import time
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
app = Flask("__name__")
app.debug = True
sockets = Sockets(app)
"""
主界面
"""
@app.route("/")
def index():
return render_template("text62.html")
"""
websocket
"""
@sockets.route("/main")
def cs(ws):
if request.environ.get('wsgi.websocket'):
ws = request.environ['wsgi.websocket'] # websocket对象
x = 0
while 1:
x+=1
if not ws.closed:
try:
ws.send(str(x))
except(IndexError):
pass
time.sleep(1)
if __name__ == "__main__":
ip=('127.0.0.1',8888)
server = pywsgi.WSGIServer(ip,application=app,handler_class=WebSocketHandler)
print(ip[0]+":"+f"{ip[1]}")
server.serve_forever()
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>text</title>
</head>
<body>
<div id="one"></div>
<script>
let ws = new WebSocket("ws://localhost:8888/main");
ws.onmessage = function (event) {
document.getElementById('one').innerHTML = event.data;
};
</script>
</body>
</html>