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>There are input/output buffers at all steps along the way between your source and destination.   Once a buffer fills, nothing else will be accepted on to it until space has been made available.</p>

<p>As your application attempts to send data, it will fill up a buffer in the operating system that is cleared as the operating system is able to offload that data to the network device driver (which also has a buffer).   </p>

<p>The network device driver interfaces with the actual network and understands how to know when it can send data and how receipt will be confirmed by the other side (if at all).   As data is sent, that buffer is emptied, allowing the OS to push more data from its buffer.   That, in turn, frees up room for your application to push more of its data to the OS.</p>

<p>There are a bunch of other things that factor into this process (timeouts, max hops are two I can think off offhand), but the general process is that you have to buffer the data at each step until it can be sent to the next step.</p>

python sockets