Search code examples
python-3.xudpfile-transferlarge-files

UDP socket file transfer python 3.5


How do i transfer a large file (video,audio) from my client to server in the local host using UDP sockets in python 3.5? I was able to send a small .txt file but not other file types. Please give me suggestions. Thank you!

Here is my code to transfer a text file.

CLIENT CODE:

import socket
import sys

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

host = '127.0.0.1'
port=6000

msg="Trial msg"

msg=msg.encode('utf-8')

while 1:

    s.sendto(msg,(host,port))
    data, servaddr = s.recvfrom(1024)
    data=data.decode('utf-8')
    print("Server reply:", data)
    break
s.settimeout(5)   

filehandle=open("testing.txt","rb")

finalmsg=filehandle.read(1024)

s.sendto(finalmsg, (host,port))

SERVER CODE:

import socket

host='127.0.0.1'

port=6000

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

s.bind(("",port))

print("waiting on port:", port)

while 1:

    data, clientaddr= s.recvfrom(1024)
    data=data.decode('utf-8')
    print(data)
    s.settimeout(4)
    break

reply="Got it thanks!"

reply=reply.encode('utf-8')

s.sendto(reply,clientaddr)

clientmsg, clientaddr=s.recvfrom(1024)

Solution

  • Don't use UDP for transferring large files, use TCP.

    UDP does not garauntee all packets you send will arrive, or if they will arrive in order, they may even be duplicated. Furthermore UDP is not suited to large transfers because 1) it has no congestion control so you will just flood the network and the packets will be dropped, and, 2) you would have to break up your packets into smaller ones usually about 1400 bytes is recommended to keep under MTU otherwise if you rely on IP fragmentation and one fragment is lost your whole file is lost .. You would have to write custom code to fix all these issues with UDP since file transfers require everything to be sent reliably.

    TCP on the other hand already does all this, it is reliable, has congestion control and is ubiquitous - you are viewing this web page over HTTP which is on top of TCP.