【发布时间】:2019-10-25 17:05:25
【问题描述】:
我的服务器使用 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 秒看到一次“测试停止”。
理论上,我想要一个 randomint> 80 到达,然后计时器停止并在找到一个数字
【问题讨论】: