I need to simulate a UDP server, which sends content of a text file line by line in an endless loop. I have written the code below but at the other end I do not receive anything (The other side is Qt code and I am sure it works):
# setup UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sa = ('localhost', 9763)
filename = '/home/saeid/Documents/data.txt' # file to read
numlines = sum(1 for line in open(filename)) # get number of lines in file
# get line of a file
with open(filename) as fp:
for i, l in enumerate(fp):
if i == line:
# main loop
currline = 0
while currline < numlines:
currline += 1
For starters this is messed up:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sa = ('localhost', 9763) sock.bind(sa) ... sock.sendto(get_line(currline), sa)
By binding you basically say "I want to listen on that host/port". But then you send the data to the same host/port. I assume that there's some other destination address, e.g.
sock.sendto(get_line(currline), ('my_host', 1234)). By the way, why are you binding to the address anyway?
sock.bind(sa) line is unnecessary, remove it.
The other thing is that your file reading code is extremely inefficient and difficult to read (it took me a while to understand what's going on). Try something like this:
with open(filename, 'r') as fo: while True: for line in fo: sock.sendto(line, DEST_ADDRESS) time.sleep(1) fo.seek(0) # go back to the begining of the file and repeat
and get rid of
That's at least what I've came up with after reading your description. If you don't want to inifinitely send the same file then you can get rid of
while True: loop and