我正在尝试使用 Pygame 和 asyncio 编写一个网络游戏,但我不知道如何避免挂起读取。这是我为客户提供的代码:
@asyncio.coroutine
def handle_client():
print("Connected!")
reader, writer = yield from asyncio.open_connection('localhost', 8000)
while True:
mouse_up = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
mouse_up = True
if mouse_up:
print("Writing")
writer.write(b"Mouse up")
print("Waiting to read")
line = yield from reader.read(2**12)
print(line.decode())
writer.close()
这个挂在网上line = yield from reader.read(2**12)
。我之前认为 asyncio 的要点在于它是非阻塞的,因此如果没有任何数据要读取,它就会继续执行。我现在发现事实并非如此。
如何将 asyncio 网络代码与 Pygame 绘图和事件代码集成?
要点是yield from
是将执行切换到 asyncio 的事件循环and阻止当前协程直到结果可用。要在不阻塞当前协程的情况下安排任务,您可以使用asyncio.async()
.
要在不阻塞 pygame 循环的情况下打印到目前为止读取的数据:
@asyncio.coroutine
def read(reader, callback):
while True:
data = yield from reader.read(2**12)
if not data: # EOF
break
callback(data)
@asyncio.coroutine
def echo_client():
reader, ...
chunks = []
asyncio.async(read(reader, chunks.append))
while True:
pygame.event.pump() # advance pygame event loop
...
if chunks: # print read-so-far data
print(b''.join(chunks).decode())
del chunks[:]
yield from asyncio.sleep(0.016) # advance asyncio loop
内部不应该有阻塞调用while
loop.
read()
and sleep()
协程在同一个线程中同时运行(显然您也可以同时运行其他协程)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)