Python网络套接字,每隔一段时间发送消息,也从客户端接收消息

时间:2019-11-06 18:04:10

标签: websocket

我从websockets开始,需要编写下一个行为:

当客户端连接从服务器接收json数据时 并且每10秒钟会收到一条相同的消息。

同时也接收传入的数据并发送相应的响应。

此代码每3秒发送一条消息:

https://websockets.readthedocs.io/en/stable/intro.html#browser-based-example

async def time(websocket, path):
    while True:
        now = datetime.datetime.utcnow().isoformat() + "Z"
        await websocket.send(now)
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, "127.0.0.1", 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

我的代码接收数据并发送响应。

async def processor(websocket, path):

    while True:
        try:
            message = await websocket.recv()

        except websockets.ConnectionClosed:
            print("Terminated")
            break

        data = json.loads(message)
        if data["action"] == "getEndStops":                
                print("getEndStops")
                await websocket.send(json.dumps(jsonEndStops))

        elif data["action"] == "getGPS":                
                print("getGPS")
                await websocket.send(json.dumps(jsonGPS))



start_server = websockets.serve(processor, "127.0.0.1", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever() 

有人知道如何混合两者??

0 个答案:

没有答案