如何用iter来获取socket的所有数据

使用socket读取网络数据,常常用while循环不断读取直到为空:

from socket import socket, AF_INET, SOCK_STREAM

def conn_example1(website):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((website, 80))
    header = 'GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n'.format(website)
    s.send(header.encode("utf-8"))
    resp = b''
    while True:
        data = s.recv(100)
        if not data:
            break
        resp += data
    s.close()
    print('len =', len(resp))

conn_example1('news.sina.com.cn')

输出

len = 470

其实该循环可以用iter来代替:

from socket import socket, AF_INET, SOCK_STREAM
from functools import partial

def conn_example2(website):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((website, 80))
    header = 'GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n'.format(website)
    s.send(header.encode("utf-8"))
    resp = b''.join(iter(partial(s.recv, 100), b''))
    s.close()
    print('len =', len(resp))

conn_example2('news.sina.com.cn')

输出

len = 470

上面代码中iter的doc如下,因此它会不断调用 callable, 直到返回空为止:

"""
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
    
Get an iterator from an object.  In the first form, the argument must supply 
its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
"""

socket.recv函数签名如下,当接收完毕时返回b''

socket.recv(bufsize[, flags])
"""
Receive up to buffersize bytes from the socket.  For the optional flags
argument, see the Unix manual.  When no data is available, block until
at least one byte is available or until the remote end is closed.  When
the remote end is closed and all data is read, return the empty string.
"""
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容