我有點新ASYNCIO和異步高清/ AWAIT語法,所以我想問問我應該如何準確做這樣的事情:ASYNCIO延遲StreamReader.read
import asyncio
import pygame
import logging
from pygame import *
log = logging.getLogger('')
class Client:
def __init__(self, host, port):
self.host = host
self.port = port
self.loop = asyncio.get_event_loop()
self.loop.run_until_complete(self.create_client())
async def create_client(self):
self.reader, self.writer = await asyncio.open_connection(self.host,
self.port,
loop=self.loop)
asyncio.ensure_future(self._handle_packets(), loop=self.loop)
async def _handle_packets(self):
while True:
data = await self.reader.read(4096)
if not data:
continue
message = data.decode()
log.debug("(NET) Received "+message)
def send(self, data):
self.loop.run_until_complete(asyncio.ensure_future(self._send(data),
loop=self.loop))
async def _send(self, data):
self.writer.write(data)
await self.writer.drain()
print("_send done")
def disconnect(self):
print("DC")
self.loop.close()
def main():
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Pyond client")
bg = Surface((640, 480))
bg.fill(Color("#004400"))
client = Client('127.0.0.1', 2508)
while True:
pygame.event.pump()
for e in pygame.event.get():
if e.type == QUIT:
raise SystemExit
elif e.type == KEYUP:
if e.key == K_UP:
client.send(b"{'Hello':'World'}")
screen.blit(bg, (0, 0))
pygame.display.update()
client.disconnect()
if __name__ == "__main__":
main()
此代碼創建640x480的窗口pygame的,然後讀取傳入的K_UP(向上箭頭)鍵。按下後,將類似json的字符串發送到服務器。 _handle_packets
應該讀取來自服務器的任何傳入數據,並將其打印出來。 我正在測試此代碼併發送工作正常,但接收延遲很大。我確定我需要把處理程序放在別的地方,所以到底在哪裏? 而順便說一句,只發送作品一次。這個也需要幫助。