Non-blocking I/O with asyncio

前端 未结 3 666
小鲜肉
小鲜肉 2021-02-01 05:22

I\'m trying to write a networked game with Pygame and asyncio, but I can\'t work out how to avoid hanging on reads. Here is my code for the client:

@asyncio.coro         


        
3条回答
  •  感动是毒
    2021-02-01 05:47

    well since you are trying to read the value of 'line' right after you call read() you need that value at any cost...

    if the coroutine wouldn't stop cause there are no data, you could get an AttributeError on the line.decode() call if 'line' then is None.

    one thing you can do is to set a timeout on the blocking call and handle the timeout exception:

    ...
    print("Waiting to read")
    try:  # block at most for one second
        line = yield from asyncio.wait_for(reader.read(2**12), 1)
    except asyncio.TimeoutError:
        continue
    else:
        print(line.decode())
    ...
    

提交回复
热议问题