V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
RandomAccess
V2EX  ›  Python

关于 Python asyncio StreamReader 读取的疑惑

  •  
  •   RandomAccess · 2021-03-03 11:45:21 +08:00 · 1075 次点击
    这是一个创建于 1122 天前的主题,其中的信息可能已经有所发展或是发生改变。
    async def hanlder(reader, writer):
        data = b""
        while not reader.at_eof():
        	_ = await reader.read(1024)
            data += _
        ...
    

    客户端建立了一个 TCP 链接后,发送了一个 http 请求,大小不固定,传送的 binary data 按道理是在 buffer 中,然后用 read 循环读取,判断直到 buffer is empty,然后解析请求的数据,但是实际情况是循环不退出

    如果使用

    async def hanlder(reader, writer):
        data = b""
        while True:
        	_ = await reader.read(1024)
            if not _:
            	break
            data += _
        ...
    

    客户端主动关闭 TCP 链接后才会退出循环 在源码中 at_eof()是需要"buffer is empty and 'feed_eof' was called" 官方文档中关于 feed_eof()的信息基本没有,求大佬解答

    1 条回复    2021-03-03 16:47:09 +08:00
    todd7zhang
        1
    todd7zhang  
       2021-03-03 16:47:09 +08:00
    tcp 是一个流嘛, 如果你客户端的 tcp 不主动告诉服务端我的数据全部发完了,那么服务端就不会认为这个 socket eof.
    所以你需要在客户端 socket 数据发完之后,sock.shutdown(1) 告诉服务端,这边数据发送完毕。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2744 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 12:39 · PVG 20:39 · LAX 05:39 · JFK 08:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.