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>Just send those bytes in a loop until all were sent, here's an <a href="https://docs.python.org/2/howto/sockets.html#using-a-socket" rel="nofollow">example from the docs</a></p>

<pre><code>def mysend(self, msg):
    totalsent = 0
    while totalsent &lt; MSGLEN:
        sent = self.sock.send(msg[totalsent:])
        if sent == 0:
            raise RuntimeError("socket connection broken")
        totalsent = totalsent + sent
</code></pre>

<p>In your case, <code>MSGLEN</code> would be 1024, and since you're not using a class, you don't need the self argument</p>

python sockets