【问题标题】:Why does StreamReader.readexactly() cause a socket error but not StreamReader.read()?为什么 StreamReader.readexactly() 会导致套接字错误而不是 StreamReader.read()?
【发布时间】:2017-10-18 08:02:11
【问题描述】:

我正在使用 Asyncio 在 python 中编写应用程序以进行网络连接。我也有类似的代码:

try:
    data = await self._reader.readexactly(10000)

    # Code that uses data
except IncompleteReadError as e:
    data = e.parial
    # More code

当我尝试运行此代码时,它似乎从未真正运行过。如果我在第二行设置断点,断点会跳闸,但函数的其余部分将被忽略。

我最接近错误的是来自 asyncio 记录器:

Traceback (most recent call last):
  File "c:\python36\Lib\asyncio\selector_events.py", line 724, in _read_ready
    data = self._sock.recv(self.max_size)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

data = await self._reader.read(10000) 替换第二行似乎可以解决这个问题,但是read() 并不能解决我的问题,我需要使用readexactly()。那么为什么readexactly() 会导致套接字错误而read() 不会呢?

【问题讨论】:

    标签: python sockets python-asyncio


    【解决方案1】:

    两者之间的唯一区别是“读取”向上读取到 n 个字节,而 readexactly 读取 完全 n 个字节,如果在 n 个字节之前到达末尾,则会引发IncompleteReadError ,这可能会导致您的套接字收到您指出的错误。

    【讨论】:

    • 那么为什么不运行 except 块?该函数只是在该行完全终止。
    • 因为你只捕获 "IncompleteReadError " ,尝试将其更改为 "Exception" 并查看 except 块是否被执行以及抛出的异常类型是什么
    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 2021-04-22
    • 2013-05-31
    • 2017-07-30
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多