我使用以下Python代码使用zeromq在服务器和客户端之间传输大文件。
发送文件,服务器的实施
CHUNK_SIZE = 250000
message = pair.recv() # message is the path to the file
filename = open(message, 'rb')
filesize = os.path.getsize(message)
offsets = (int(ceil(filesize / CHUNK_SIZE)), 0)[filesize <= CHUNK_SIZE]
for offset in range(offsets + 1):
filename.seek(offset)
chunksize = CHUNK_SIZE
if offset == offsets:
chunksize = filesize - (CHUNK_SIZE * (offset - 1)) # calculate the size of the last chunk
data = filename.read(chunksize)
pair.send(data)
pair.send(b'')
接收文件,客户端的实施
while True:
data = pairs.recv()
if data is not '':
target.write(data)
else:
break
但是,在使用此实现传输大文件后,由于某种原因,在文件末尾添加了额外的数据:
文件服务器端
$ stat file.zip
File: `file.zip'
Size: 1503656416 Blocks: 2936840 IO Block: 4096 regular file
客户端
$ stat file.zip
File: `file.zip'
Size: 1503906416 Blocks: 2937328 IO Block: 4096 regular file
它们之间的大小和块是不同的。
那就是说,你有什么建议可以正确计算/发送文件结尾吗?
由于
答案 0 :(得分:1)
刚刚找到解决方案。 seek()
没有正确处理这些块。
-filename.seek(offset)
+filename.seek(0, 1)
因此,它总是在当前(最后)位置获得偏移量0。
现在一切都按预期工作:)