使用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.
"""
网友评论