我有一个客户端和一个服务器,服务器需要向客户端发送许多文本文件。
发送文件函数接收套接字和要发送的文件的路径:
CHUNKSIZE = 1_000_000
def send_file(sock, filepath):
with open(filepath, 'rb') as f:
sock.sendall(f'{os.path.getsize(filepath)}'.encode() + b'\r\n')
# Send the file in chunks so large files can be handled.
while True:
data = f.read(CHUNKSIZE)
if not data:
break
sock.send(data)
接收文件函数接收客户端套接字和保存传入文件的路径:
CHUNKSIZE = 1_000_000
def receive_file(sock, filepath):
with sock.makefile('rb') as file_socket:
length = int(file_socket.readline())
# Read the data in chunks so it can handle large files.
with open(filepath, 'wb') as f:
while length:
chunk = min(length, CHUNKSIZE)
data = file_socket.read(chunk)
if not data:
break
f.write(data)
length -= len(data)
if length != 0:
print('Invalid download.')
else:
print('Done.')
它的工作原理是将文件大小作为第一行发送,然后逐行发送文本文件。
两者都是在客户端和服务端循环调用,从而将文件一一发送并保存。
如果我设置断点并缓慢调用这些函数,效果会很好。但是如果我让程序不间断地运行,它在读取第二个文件的大小时会失败:
File "/home/stark/Work/test/networking.py", line 29, in receive_file
length = int(file_socket.readline())
ValueError: invalid literal for int() with base 10: b'00,1851,-34,-58,782,-11.91,13.87,-99.55,1730,-16,-32,545,-12.12,19.70,-99.55,1564,-8,-10,177,-12.53,24.90,-99.55,1564,-8,-5,88,-12.53,25.99,-99.55,1564,-8,-3,43,-12.53,26.54,-99.55,0,60,0\r\n'
显然,该线路正在接收更多的数据length = int(file_socket.readline())。
我的问题:这是为什么?鉴于该行始终以尾随发送,难道该行不应该只读取大小吗\n?
如何解决此问题以便可以连续发送多个文件?
冉冉说
缥缈止盈
相关分类