-1

I'm trying to transfer files with python socket module, I can transfer and write the file but I can't stop the function when there are no more bytes to write

FORMAT="utf-8"
HEADER=512

CLIENT CODE

FORMAT="utf-8"
HEADER=512
def File(path):
    name=os.path.basename(path)
    client.send("file".encode(FORMAT))
    client.send(name.encode(FORMAT))
    print(client.recv(HEADER).decode(FORMAT))
    f=open(path,"rb")
    l=f.read(HEADER)
    while (l):
        client.send(l)
        l=f.read(HEADER)
    f.close()
    print("Finish")

SERVER CODE

def Save(conn):
  name=(conn.recv(HEADER).decode(FORMAT))
  conn.send(f"Saving {name}".encode(FORMAT))
  print(name)
  Writing=True
  with open(PATH+name,"wb") as f:
      print("Writing file")
      while Writing:
          data=conn.recv(HEADER)
          if not data:
              Writing=False
          f.write(data)
      f.close()
      print("File written")
  conn.close()
cipryyyy
  • 39
  • 1
  • 8
  • Try follow [PEP8's naming convention](https://www.python.org/dev/peps/pep-0008/#naming-conventions), namely that functions and should be written in `lower_snake_case` and classes in `PascalCase`. The capitalization you use has a semantic meaning to programmers. Also, try to space out code with some newlines to separate logical segments of code (if you don't know how just do it randomly once in a while). Lastly, put a space around operators as `=`, `+`, `-` and such. This helps to space out lines so they read as words in a sentence instead of just a single run-on sentence. – Ted Klein Bergman Aug 23 '20 at 09:01
  • @TedKleinBergman HEADER and FORMAT are constants, anyway thank you for the link, I didn't know there was a document about it. – cipryyyy Aug 23 '20 at 10:13
  • Yes, and that is correct! I was thinking that `Writing` is how you write classes, which in bigger programs might make it confusing as it's a variable. The same with `File` and `Save` are functions but are written as if they were classes. – Ted Klein Bergman Aug 23 '20 at 10:30
  • Ty, I'll fix it – cipryyyy Aug 23 '20 at 10:41

1 Answers1

1

To know when a socket has finished, take a look at How does the python socket.recv() method know that the end of the message has been reached?.
Anyway, receiving constant HEADER size is a bad practice, as the received amount can be smaller (due to network issues);
You'd better keep up with the actual amount received with respect to the desired amount, like in this example:

    def receive(self, size):
        from_client = b''
        remaining_to_recive = size    
        while 0 < remaining_to_recive:
             data = self.sock.recv(remaining_to_recive)
             if not data: break             
             from_client += data
             remaining_to_recive -= len(data)  
        if 0 < remaining_to_recive:
            raise RuntimeError(Connection.NOT_ALL_DATA_RECEIVED_ERROR)
        return from_client 
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22