I'm trying to send data over UDP point to point (looping back to a second NIC) but am losing data. Here is the code (from: sending/receiving file UDP in python):
----- sender.py ------
#!/usr/bin/env python
from socket import *
import sys
s = socket(AF_INET,SOCK_DGRAM)
host =sys.argv[1]
port = 9999
buf =1024
addr = (host,port)
file_name=sys.argv[2]
s.sendto(file_name,addr)
f=open(file_name,"rb")
data = f.read(buf)
while (data):
if(s.sendto(data,addr)):
#print "sending ..."
data = f.read(buf)
s.close()
f.close()
----- receiver.py -----
#!/usr/bin/env python
from socket import *
import sys
import select
host="192.0.0.2" #second nic
port = 9999
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))
addr = (host,port)
buf=1024
data,addr = s.recvfrom(buf)
print "Received File:",data.strip()
f = open(data.strip(),'wb')
data,addr = s.recvfrom(buf)
try:
while(data):
f.write(data)
s.settimeout(2)
data,addr = s.recvfrom(buf)
except timeout:
f.close()
s.close()
print "File Downloaded"
I create my file with dd:
dd if=/dev/urandom of=test_file bs=1024 count=100
I found that when count is over approx 100 it starts to fail. I tried different bs all the way down to 32 and it still fails. When I change bs I change buf in the code to match. I repeat creating a new file and running the command in a loop. With different combinations, sometimes it fails every transfer, sometimes it fails in a pattern (ie every 5)
I found that if I add a delay in the while loop in sender to delay by 0.0005 seconds, then it works fine and I can send any amount of data. If I bring the delay down to 0.0001, then it fails again. I'm getting approx 1.5MB/sec
I'd appreciate any recommendations to improve my performance. I am thinking that perhaps there is a receive buffer that is overflowing and I'm just not reading it fast enough.