【问题标题】:How to send JSON every 3 seconds with websocket [Python server, js client]如何使用 websocket 每 3 秒发送一次 JSON [Python 服务器,js 客户端]
【发布时间】: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 到达,然后计时器停止并在找到一个数字

【问题讨论】:

    标签: python websocket timer


    【解决方案1】:

    考虑在您的while True 语句中使用time.sleep(X) 而不是计时器。

    【讨论】:

      猜你喜欢
      • 2022-07-15
      • 1970-01-01
      • 2015-08-17
      • 2012-05-10
      • 1970-01-01
      • 2018-10-25
      • 2017-09-15
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多