mtoy
mtoy

Reputation: 195

Python: sending large files between computers

I'm trying send a file (~340 MB) from one computer to another in a company network.

When sending is finished another computer received ~325 MB.
~ 15 MB has been lost.

I run my client script on the computer 192.169.0.5

python3 client.py

And later I run my server script on 192.168.0.4

python3 server.py 192.168.0.5 test.sql

My Server source code is:

s = socket(AF_INET,SOCK_DGRAM)
host = sys.argv[1]
port = 9999
buf = 4096
addr = (host,port)

s.connect((host , port))


file_name=sys.argv[2]

f=open(file_name,"rb")
data = f.read(buf)
print('Sending file '+ file_name +' ...')

sent_size = 0

while True:
    if(s.send(data)):

        sent_size += buf
        mb = round(sent_size / 1024 / 1024, 2)
        sys.stdout.write("\rSent: "+ str(mb) +" MB")
        sys.stdout.flush()

        time.sleep(0.001)
        data = f.read(buf)

    else:
        print('\n- Finished')
        s.close()
        break

My Client source code is:

host="0.0.0.0"
port = 9999
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))

addr = (host,port)
buf=4096



while True:

    data,addr = s.recvfrom(buf)

    if data:

        data,addr = s.recvfrom(buf)
        b2 = 0

        f = open("recv/received.deb",'wb')

        while(data):
            f.write(data)
            s.settimeout(2)
            b2 += buf
            mb = round(b2 / 1024 / 1024, 2)
            sys.stdout.write("\rReceived: "+ str(mb) +" MB")
            sys.stdout.flush()
            data,addr = s.recvfrom(buf)

        break

Everything works for small files (~1MB) but if we want to send a bigger file (300MB) packets are lost.. How can I fix this issue ?

Upvotes: 2

Views: 2388

Answers (1)

Rutrus
Rutrus

Reputation: 1467

Reading your code, you are using sockets over UDP. You must use SOCK_STREAM

s = socket(AF_INET,SOCK_STREAM)
host = sys.argv[1]
port = 9999
buf = 4096
addr = (host,port)

So, you must change both scripts to send files. For a local network, I recommend to use the easy way:

python3 -m http.server

And access from the client with a web browser. It will show the local folder.

Upvotes: 1

Related Questions