使用 python socketio 包,我創建了一個定時器,當客戶端連接到我的服務器時啟動。
服務器端代碼:
import socketio
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
'/': './public/'。
})
@sio.event
def connect(sid, environ):
count = 10
while count > 0:
sio.emit('timer_count', count)
sio.sleep(1)
count -=1
供參考的HTML代碼(index.html):
<!doctype html>
<html>
<head>
<title>Timer</title>
</head>/span>
<body>
<h1>Timer Build</h1>
<p1 id="counter"/span>> </p1>>
<script src="https://cdnjs. cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.min.js"></script>/span>
<script src="/index. js"></script>>
</body>
</html>
客戶端JS代碼(index.js):
const sio = io();
sio.on('timer_count',function(count) {
console.log(計數)。
var s = document.getElementById("counter"/span>)。
s.innerHTML = count;
});
然而,我得到的行為是,在服務器端代碼執行完畢之前,資料不會被發送到客戶端(即,整個計數被一次性列印出來)。我怎樣才能讓它以真正的定時器方式表現出來,讓 console.log() 函式每秒鐘列印一次資料(計數)?
uj5u.com熱心網友回復:
你在connect事件處理程式中加入了你的回圈,它是用來接受或拒絕連接的。在你從這個處理程式回傳之前,Socket.IO 連接不會被完全建立。
將你的回圈移到一個單獨的事件中,在 connect 處理程式回傳并接受連接后執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/332999.html
標籤:
上一篇:Nginxwwwtononwwwwithpagenotworking
下一篇:對所有下拉值的回圈腳本
