title: Transferring File over TCP using Python
body: <p>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 useful </p>
  
  <p>Client Side</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Server Side</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Now i have two problems with this code
  First </p>
  
  <pre><code>self._con.sendall(encode_length(len(data)))
  </code></pre>
  
  <p>in this line it gives me an error saying encode_length is undefined</p>
  
  <p>Secondly these are functions that send and receive file
  Where do i call them 
  Do i first form a TCP Connection and then call these functions
  And how exactly to call them , if i call them directly it gives me an error on client side saying _sendFile(self, path) takes two arguments  (since i am not passing self just the path)</p>
  
  <p>Thirdly i am using function from os library to get complete path , So i am calling the function like</p>
  
  <pre><code>_sendFile(os.path.abspath("file_1.txt"))
  </code></pre>
  
  <p>is this the correct way to pass the argument</p>
  
  <p>Sorry i know this question is pretty basic and lame but everywhere online i can basically get the function but not how to call it </p>
  
  <p>right now this is how i am calling the function</p>
  
  <pre><code>serverIP = '192.168.0.102'
  serverPort = 21000
  
  clientSocket = socket(AF_INET, SOCK_STREAM)
  
  message = "Want to Backup a Directory"
  
  
  clientSocket.connect((serverIP, serverPort))
  
  _sendFile(os.path.abspath("file_1.txt"))
  </code></pre>
  
  <p>Which is basically wrong</p>
  
  <p>I am using the same computer for both Client and Server</p>
  
  <p>Running Python on Ubuntu using terminal </p>