PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] how to modify this code to transfer files faster?

 October 22, 2022     file-transfer, python, sockets     No comments   

Issue

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")

Solution

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")


Answered By - Mark Tolonen
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing