虽然您遇到的第一个问题是不将接收到的最后一块数据写入输出文件,但还有其他一些问题.
您可以通过将if语句更改为以下内容来解决当前问题:
if (rec.endswith(b'FIN')):
writefile.write(rec[:-3]) # Ignore the last 3 bytes
break
您还有其他问题:
>如果文件中包含字符FIN,则1024中大约有1个字符将成为读取缓冲区中的最后3个字符,并且您的代码将错误地将其读取为结束标记,并过早终止.
>在1024中也有2的可能性将FIN标记拆分为两次对read()的调用,而rec以F或FI结尾.
这两个问题都是由TCP是基于流的协议引起的,在用户级别没有数据包的概念.
一个明显的解决方法是,在文件传输之前使用固定的大小长度指示,让接收者读取该指示,然后读取正确的字节数.
像这样:
def _sendFile(self, path):
sendfile = open(path, 'rb')
data = sendfile.read()
self._con.sendall(encode_length(len(data)) # Send the length as a fixed size message
self._con.sendall(data)
# Get Acknowledgement
self._con.recv(1) # Just 1 byte
def _recieveFile(self, path):
LENGTH_SIZE = 4 # length is a 4 byte int.
# Recieve the file from the client
writefile = open(path, 'wb')
length = decode_length(self.con.read(LENGTH_SIZE) # Read a fixed length integer, 2 or 4 bytes
while (length):
rec = self.con.recv(min(1024, length))
writefile.write(rec)
length -= sizeof(rec)
self.con.send(b'A') # single character A to prevent issues with buffering
当然,在发送/接收长度时,您需要知道长度字段中的字节顺序.