为什么 StreamReader 无法在此代码中接收?

Why StreamReader can't recv in this code?

我有一个关于 StreamReader/StreamWriter 的问题。

为了简化我的实际代码,就像下面的代码一样(他们可以运行)。在 运行 连接服务器后,运行 客户端请求它。服务器不会读取任何数据

服务器代码:

import asyncio

loop = asyncio.get_event_loop()


async def log(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
    print("Wait read")
    data = await reader.read(-1)
    print("<:", data)
    writer.write(data)
    await writer.drain()
    print(">:", data)


async def link(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
    asyncio.run_coroutine_threadsafe(log(reader, writer), loop)
    print("Connect.")
    await asyncio.sleep(1)


loop.run_until_complete(
    asyncio.start_server(
        link, "0.0.0.0", 1080, loop=loop
    )
)
loop.run_forever()

客户代码:

import socket
import traceback

try:
    sock = socket.create_connection(("127.0.0.1", 1080))
    sock.sendall(b"Hello")
    print(sock.recv(1024))
    sock.close()
except socket.error:
    traceback.print_exc()

我知道如何解决这个问题,但我想知道为什么会出现这个问题。

根据documentation :

StreamReader.coroutine read(n=-1)

Read up to n bytes. If n is not provided, or set to -1, read until EOF and return all read bytes.

If EOF was received and the internal buffer is empty, return an empty bytes object.

您的程序正在等待调用 data = await reader.read(-1)reader.read(-1) return 只有当它接收到EOF(文件结束)时。换句话说,这意味着当另一端(客户端)关闭套接字时它将 return。

您可以尝试在客户端代码中注释掉这一行 print(sock.recv(1024)) ,您将看到 data = await reader.read(-1) returns.