Home > OS >  how to modify this code to transfer files faster?
how to modify this code to transfer files faster?

Time:07-18

I wrote that simple client/server code in order to transfer files. the code transferred pictures and text files pretty easily and very fast. but it takes a long time to transfer an mp4 file (more than 10 minutes). how do I modify it to run faster? thank you

the server:

import socket
import os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 12345))

s.listen(10)
c, addr = s.accept()
print('{} connected.'.format(addr))

f = open("test.png", "rb")
l = os.path.getsize("test.png")
m = f.read(l)
c.sendall(m)
f.close()
print("Done sending...")

and the client:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 12345))

f = open("received.jpg", "wb")
data = None
while True:
    m = s.recv(1024)
    data = m
    if m:
        while m:
            m = s.recv(1024)
            data  = m
        else:
            break
f.write(data)
f.close()
print("Done receiving")

CodePudding user response:

Write as you receive and with a larger buffer.

Also use with to ensure the socket and file are closed.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 12345))

with s, open("received.jpg", "wb") as f:
    while data := s.recv(1024*1024):
        f.write(data)

print("Done receiving")
  • Related