【问题标题】:Update Server every n seconds by looping function every n seconds? Python Sockets通过每 n 秒循环一次函数来每 n 秒更新一次服务器? Python 套接字
【发布时间】:2020-06-18 18:45:50
【问题描述】:

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

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

我该怎么办?

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)

【问题讨论】:

    标签: python websocket udp python-asyncio


    【解决方案1】:

    您不能在 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())
    

    【讨论】:

    • 我可以打电话问你几个问题吗?我愿意付出!在此先感谢 :) @user4815162342
    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多