每n秒循环一次功能是否每隔n秒更新一次服务器? Python套接字

时间:2020-06-18 18:45:50

标签: python websocket udp python-asyncio

我正在运行这台接收数据的服务器。但是我希望它每秒更新一次。这个Asyncio循环说它永远运行,但是只接收一次数据。

我可以执行哪些循环来每n秒更新一次消息检索,我应该将这些循环放在哪里?我曾经尝试过线程,For /循环循环等,但是我可能将它们放在错误的位置。

我该怎么办?

import asyncio
    import websockets
    import socket

    UDP_IP = socket.gethostname()
    UDP_PORT = 5225

    sock = socket.socket(socket.AF_INET, # Internet
                         socket.SOCK_DGRAM) # UDP
    sock.bind((UDP_IP, UDP_PORT))

    while True:
        data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
        #print(str(data))


        x = 1

        async def echo(websocket, path):
            async for message in websocket:
                await asyncio.sleep(1)
                await websocket.send(str(data)) #FontWeight Value



        print(bytes(data))


        start_server = websockets.serve(echo, "localhost", 9090)


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

1 个答案:

答案 0 :(得分:0)

您不能在asyncio中使用普通套接字,因为它们的阻塞recv使事件循环停止。您需要使用以下内容:

data = None

class ServerProtocol(asyncio.Protocol):
    def data_received(self, newdata):
        global data
        data = newdata

async def serve_udp():
    loop = asyncio.get_running_loop()
    server = await loop.create_server(ServerProtocol, UDP_IP, UDP_PORT)
    async with server:
        await server.serve_forever()

然后将其与websocket服务代码集成。例如:

async def ws_echo(websocket, path):
    async for message in websocket:
        await asyncio.sleep(1)
        await websocket.send(str(data))

async def main():
    asyncio.create_task(serve_udp())
    await websockets.serve(ws_echo, "localhost", 9090)
    await asyncio.Event().wait()  # prevent main() from returning

asyncio.run(main())