File Transfer Over TCP Using Python

I am currently working on a python project that requires transferring files from client to server through a Python socket. Here is my current code, which, however, does not transfer the entire file, but depending on the size of the file, there are always some bites or extra bytes.

_con and con are connections to shell wrappers through a python socket.

Customer:

def _sendFile(self, path):
    sendfile = open(path, 'rb')
    data = sendfile.read()

    self._con.sendall(data)

    self._con.send(bytes('FIN', 'utf8'))
    # Get Acknowledgement
    self._con.recv(6)

def _recieveFile(self, path):
    # Recieve the file from the client
    writefile = open(path, 'wb')
    i = 0
    while (1):
        rec = self.con.recv(1024)
        if (rec.endswith(b'FIN')):
            break
        writefile.write(rec)

    self.con.send(b'ACK')
+3
source share
2 answers

While the first problem is that you did not write the last piece of data received in the output file, you have a few more problems.

The current problem can be fixed by changing the instructions ifto the following:

if (rec.endswith(b'FIN')):
    writefile.write(rec[:-3]) # Ignore the last 3 bytes
    break

You still have other problems:

  • FIN, , , 1, , , .

  • , 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

, / .

+5

, , FIN, . , . , .

while (1):
    rec = self.con.recv(1024)
    if (rec.endswith(b'FIN')):
        break
    writefile.write(rec)
0

Source: https://habr.com/ru/post/1792607/


All Articles