如何使用websocket每3秒发送JSON [Python服务器,js客户端]

时间:2019-06-11 09:46:28

标签: python websocket timer

我有使用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秒收到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到来后立即停止,然后计时器在找到数字<80时再次启动。

1 个答案:

答案 0 :(得分:0)

请考虑在您的time.sleep(X)语句中使用while True代替计时器。