![](/img/trans.png)
[英]Initial delay whilst looping a function every n seconds in Python 2.7
[英]Update Server every n seconds by looping function every n seconds? Python Sockets
我正在運行這個接收數據的服務器。 但是我希望它每秒更新一次。 這個 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)
您不能在 asyncio 中使用普通的 sockets 因為它們的阻塞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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.