Reputation: 3254
I am sending file using python' UDP socket. At receiver side(file_receiver.py), you need to interrupt (ctrl-c) the program in order to receive the file at the end. Therefore I put settimeout for 2 second, to program to quit automatically, once data is received completely. If I know well, you can not set non-blocking socket in UDP. what is the best way to overcome this problem.
file_sender.py
#!/usr/bin/env python
from socket import *
import sys
s = socket(AF_INET,SOCK_DGRAM)
host ="localhost"
port = 9999
buf =1024
addr = (host,port)
f=open (sys.argv[1], "rb")
data = f.read(buf)
while (data):
if(s.sendto(data,addr)):
print "sending ..."
data = f.read(buf)
s.close()
f.close()
file_receiver.py
#!/usr/bin/env python
from socket import *
import sys
import select
host="0.0.0.0"
port = 9999
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))
addr = (host,port)
buf=1024
f = open("op.pdf",'wb')
data,addr = s.recvfrom(buf)
while(data):
f.write(data)
s.settimeout(2)
data,addr = s.recvfrom(buf)
f.close()
s.close()
Thanks.
Upvotes: 1
Views: 6895
Reputation: 6115
Because UDP is connection-less, there's no straight-forward way for the receiving side to know when the sender is done.
You could work around this, for example, by sending a special packet when the sender is done that indicates that no more packets will follow.
However, I would strongly advise you against that; UDP doesn't make guarantees about delivery of packets---packets may be lost, duplicated or delivered out of order. Clearly, for most files it would be unacceptable if they were missing a part, or where reordered, etc.. If you want to transfer a file between to hosts, I think you're much better off using TCP.
Upvotes: 5