通过套接字接收的总字节数与实际文件大小不同

时间:2016-05-19 07:11:10

标签: python sockets ftp ftplib

我编写了一个程序来从FTP服务器下载文件,这里是代码:

from ftplib import FTP

host = 'x.x.x.x'
user = 'demo'
password = 'fakepw`'
path = '/mnt10/DATA/201605/'
filename = 'DATA.TXT'
ftp = FTP(host, user, password)   # connect to host, default port
ftp.cwd(path)
ftp.voidcmd('TYPE I')
sock = ftp.transfercmd('RETR ' + filename)
f = open('D:\\DATA\\' + filename, 'wb')
chunk = 1
while True:
    block = sock.recv(1024*1024)
    if not block:
        break
    print('Getting file {} bytes'.format(chunk*(1024**2)))
    chunk += 1
    f.write(block)
sock.close()

以下是运行程序的结果:

Getting file 1048576 bytes
Getting file 2097152 bytes
Getting file 3145728 bytes
Getting file 4194304 bytes
Getting file 5242880 bytes
..........................
Getting file 22020096 bytes
Getting file 23068672 bytes
Getting file 24117248 bytes
Getting file 25165824 bytes
Getting file 26214400 bytes

Process finished with exit code 0

但实际文件大小只有11.5MB左右 Real file size

我不知道为什么他们不同。

修改 正如@Martin Prikryl的回答,我改变了我的程序:

total_size = 0

while True:
    block = sock.recv(1024*1024)
    if not block:
        break
    print('Size of block: {}'.format(len(block)))
    total_size += len(block)
    f.write(block)

print('Total size: {}'.format(total_size))

sock.close()

现在程序运行良好。

Size of block: 1048576
Size of block: 6924
Size of block: 1048576
......................
Size of block: 14924
Size of block: 771276
Total size: 11523750

Process finished with exit code 0

1 个答案:

答案 0 :(得分:2)

如果套接字是异步的,则不会获得整个1024*1024个字节。您只获得可用的字节数(已经收到)。

打印block的大小,以获得准确的字节数。