[英]Update Server every n seconds by looping function every n seconds? Python Sockets
I'm running this server which receives data.我正在运行这个接收数据的服务器。 However I want it to update every second.但是我希望它每秒更新一次。 This Asyncio loop says it's running forever but it only receives data once.这个 Asyncio 循环说它永远运行,但它只接收一次数据。
What loops can I execute to update message retrieval every n seconds and where should I place these loops?我可以执行哪些循环来每 n 秒更新一次消息检索,我应该在哪里放置这些循环? I've tried Threading, For/While Loops etc but I may have been placing them in the wrong places.我尝试过线程、For/While 循环等,但我可能把它们放在了错误的地方。
What should I do?我应该怎么办?
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)
You can't use ordinary sockets in asyncio because their blocking recv
stalls the event loop.您不能在 asyncio 中使用普通的 sockets 因为它们的阻塞recv
会停止事件循环。 You need to use something like this:你需要使用这样的东西:
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()
Then you to integrate it with the websocket serving code.然后将其与 websocket 服务代码集成。 For example:例如:
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.