![](/img/trans.png)
[英]How can I monitor client side inputs and send input requests from server every 5 seconds if no input is received?
[英]How to send JSON every 3 seconds with websocket [Python server, js client]
我的Python服務器通過websocket發送JSON,代碼如下:
import asyncio
import datetime
import random
import websockets
import json
import threading
stopSignal = 0
def stopTestINT():
print("test Stop \n")
stopSignal = 1
async def wsjson(websocket, path):
while True:
data = datetime.datetime.now()
randomINT = random.randint(1, 101)
sensors_data = {
'property': {
'INT': randomINT,
'stop' : stopSignal
}
}
timer = threading.Timer(15.0, stopTestINT)
if randomINT < 80:
timer.start()
else:
timer.cancel()
print_json = json.dumps(sensors_data)
await websocket.send(print_json)
await asyncio.sleep(3)
start_server = websockets.serve(wsjson, '127.0.0.1', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
使用這個示例代碼我每3秒發送一次這個json,但在客戶端我收到(每3秒)三個randomINT。 為什么?
1.當我關閉連接時(在JS中,使用ws.close())連接沒有關閉,事實上我收到了這個錯誤:
Error in connection handler
Traceback (most recent call last):
File "C:\*\*\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websockets\server.py", line 169, in handler
yield from self.ws_handler(self, path)
File "C:\Users\*\**\websockets py\websjson.py", line 160, in wsjson
await websocket.send(print_json)
File "C:\Users\**\Python\Python37-32\lib\site-packages\websockets\protocol.py", line 462, in send
yield from self.ensure_open()
File "C:\Users\*\Python\Python37-32\lib\site-packages\websockets\protocol.py", line 646, in ensure_open
) from self.transfer_data_exc
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1005 (no status code [internal]), no reason
2.並且計時器不起作用,實際上在提示中我看到每3秒“測試停止”。
理論上,我想只要一個> 80的隨機到達,然后計時器停止並在找到一個<80的數字時再次啟動。
考慮在while True
語句中使用time.sleep(X)
而不是timer。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.