Sending And Receiving Bytes through a Socket, Depending On Your Internet Speed
<p>I made a quick program that sends a file using sockets in python.</p>

<p>Server:</p>

<pre><code>import socket, threading

#Create a socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Bind the socket.
sock.bind( ("", 5050) )

#Start listening.
sock.listen()

#Accept client.
client, addr = sock.accept()


#Open a new file jpg file.
file = open("out.jpg", "wb")


#Receive all the bytes and write them into the file.
while True:

    received = client.recv(5)

    #Stop receiving.
    if received == b'':
        file.close()
        break

    #Write bytes into the file.
    file.write( received )
</code></pre>

<p>Client:</p>

<pre><code>import socket, threading

#Create a socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Connect to the server.
sock.connect(("192.168.1.3", 5050))


#Open a file for read.
file = open("cpp.jpg", "rb")

#Read first 5 bytes.
read = file.read(5)

#Keep sending bytes until reaching EOF.
while read != b'':

    #Send bytes.
    sock.send(read)

    #Read next five bytes from the file.
    read = file.read(1024)


sock.close()
file.close()
</code></pre>

<p>From experience a learn that send can send an amount of bytes that your network
speed is capble of sending them. If you give for example: sock.send(20 gb) you are going to lose bytes because most network connections can't send 20 gb at
once. You must send them part by part.</p>

<p>So my question is: How can i know the maximum amount of bytes that socket.send()
can send over the internet? How can i improve my program to send the file as quick as possible depending on my internet speed?</p>

<p>@Jeremy Friesner</p>

<p>So I can do something like that:</p>

<pre><code>file = open(filename, "rb")

read = file.read(1024**3) #Read 1 gb.

totalsend = 0

#Send Loop
while totalsend &lt; filesize:

    #Try to send all the bytes.
    send = sock.send(read)
    totalsend += send

    #If failed, then seek into the file the position
    #where the next read will also read the missing bytes.
    if send &lt; 1024**3:
        file.seek(totalsend)

    read = file.read(1024**3) #Read 1 gb.
</code></pre>

<p>Is this correct?</p>

<p>Also, from this example i undestood one more think. The data you can send in every loop, can't be bigger in size than your memory. Because you are bringing bytes from the disk on the memory. So theoretically even if your network speed is infinity, you can't send all the bytes at once if the file is bigger than your memory.</p>

python sockets