V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Mar 3, 2021 · 1606 views
    This topic created in 1885 days ago, the information mentioned may be changed or developed.
    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 replies    2021-03-03 16:47:09 +08:00
    todd7zhang
        1
    todd7zhang  
       Mar 3, 2021
    tcp 是一个流嘛, 如果你客户端的 tcp 不主动告诉服务端我的数据全部发完了,那么服务端就不会认为这个 socket eof.
    所以你需要在客户端 socket 数据发完之后,sock.shutdown(1) 告诉服务端,这边数据发送完毕。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   923 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:22 · PVG 07:22 · LAX 16:22 · JFK 19:22
    ♥ Do have faith in what you're doing.