Skip to content Skip to sidebar Skip to footer

Transferring File Over Tcp Using Python

I am new to python and finding it really difficult trying to understand how to send files using sockets with a tcp connection i found this code in another question that seems to be

Solution 1:

First problem:

It's because you simply haven't defined functions encode/decode_lenght.


Second problem:

Your function is: def _sendFile(self, path): .... Do you know how to use self? It is used in the classes. So define it without self, or use classes:

Example:

from socket import *
classClient(object):

    def__init__(self):

        self.clientSocket = socket(AF_INET, SOCK_STREAM)

    defconnect(self, addr):

        self.clientSocket.connect(addr)

    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>>> client = Client()
>>> client.connect(("192.168.0.102", 21000))
>>> client._sendFile(os.path.abspath("file_1.txt")) # If this file is in your current directory, you may just use "file_1.txt"

And same (almost) for Server.


Where to define these functions? In the code ofcorse! What should your functions do? OK, an example:

defencode_length(l):

    #Make it 4 bytes long
    l = str(l)
    whilelen(l) < 4:
        l = "0"+l 
    return l

# Example of using>>> encode_length(4)
'0004'>>> encode_length(44)
'0044'>>> encode_length(444)
'0444'>>> encode_length(4444)
'4444'

About self:

Just a little bit:

self redirects to your current object, ex:

classsomeclass:
    def__init__(self):
        self.var = 10defget(self):
        return self.var

>>> c = someclass()
>>> c.get()
10>>> c.var = 20>>> c.get()
20>>> someclass.get(c)
20
>>>

How does someclass.get(c) work? While executing someclass.get(c), we are not creating an new instance of someclass. When we call .get() from an someclass instance, it automaticly sets self to our instance object. So someclass.get(c) == c.get() And if we try to do someclass.get(), self was not defined, so it will raise an error: TypeError: unbound method get() must be called with someclass instance as first argument (got nothing instead)


You can use decorator to call functions of a class (not its instance!):

classsomeclass:def__init__(self):
        self.var = 10defget(self):
        return10# Raises an error@classmethoddefget2(self):
        return10# Returns 10!

Sorry for my bad explanations, my English is not perfect


Here are some links:

server.py

client.py

Post a Comment for "Transferring File Over Tcp Using Python"