推荐学习书目
› 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
sbmzhcn
V2EX  ›  Python

Python 下 sock.recv 产生阻塞的解决办法

  •  
  •   sbmzhcn · Jun 16, 2015 · 6503 views
    This topic created in 4158 days ago, the information mentioned may be changed or developed.
    buf = 8192
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('192.168.1.10', 2000))
    sock.sendall(data)
    data = sock.recv(buf)
    sock.close()
    

    上面是最简单的socket连接程序,网上很多例子也是这样,但是recv这个地方如果服务器突然不响应了会产生阻塞,避免的办法网上大概有以下几个:
    1. socket.settimeout() ,这个无法避免阻塞的,行不通
    2. socket.setblocking(0) 这个必须再加个time.sleep(5)模拟阻塞,此方法兼容性很不友好。

    想请问大家有什么特别好的方法没?比如异步的写法,给个示例也行。

    11 replies  •  2015-06-17 10:33:17 +08:00
    est
    est
    Jun 16, 2015 via Android
    1
    tornado, gevent, asyncio
    binux
    binux
    Jun 16, 2015
    2
    select
    fangjinmin
    fangjinmin
    Jun 16, 2015
    3
    用epoll
    lilydjwg
    lilydjwg
    Jun 16, 2015
    4
    @binux @fangjinmin 这两个都无法解决 recv(2) 阻塞的问题——除非把套接字设置成非阻塞。

    不知道你的「无法避免阻塞」是什么意思。settimeout 会在你指定的时间之后返回的,并不会一直阻塞下去啊。你一刻也不想阻塞?可 setblocking(False) 之后,你为什么还要 sleep 呢,按之前的逻辑,这样不就「阻塞」了吗?——所以,你的需求到底是什么?
    binux
    binux
    Jun 16, 2015
    6
    @lilydjwg 套接字 read ready 的泗洪 recv 也会阻塞吗?
    hualuogeng
    hualuogeng
    Jun 16, 2015
    7
    @lilydjwg 多好的XY
    stillness
    stillness
    Jun 16, 2015
    8
    @binux 有可能,linux 的 man select 有这么一段话

    Under Linux, select() may report a socket file descriptor as "ready for
    reading", while nevertheless a subsequent read blocks. This could for
    example happen when data has arrived but upon examination has wrong
    checksum and is discarded. There may be other circumstances in which a
    file descriptor is spuriously reported as ready. Thus it may be safer
    to use O_NONBLOCK on sockets that should not block.
    way2exluren
    way2exluren
    Jun 16, 2015
    9
    python 的socket在设置timeout后。
    sock.timeout(5)
    socket就变成非阻塞socket了……
    楼主注意
    zeayes
    zeayes
    Jun 17, 2015
    10
    setblocking或者settimeout,然后catch住特定的异常处理掉,就好了。
    feisan
    feisan
    Jun 17, 2015
    11
    @way2exluren

    设置timeout会使socket变非阻塞?
    sock.settimeout(0)才相当于sock.setblocking(0)吧?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2197 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 59ms · UTC 16:06 · PVG 00:06 · LAX 08:06 · JFK 11:06
    ♥ Do have faith in what you're doing.