Search code examples
pythonpython-2.7python-sockets

Python UDP Server send lines of a text file


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):

import socket
import time

# setup UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sa = ('localhost', 9763)
sock.bind(sa)

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
def get_line(line):
    with open(filename) as fp:
        for i, l in enumerate(fp):
            if i == line:
                return l

# main loop
while True:
    currline = 0
    while currline < numlines:
        sock.sendto(get_line(currline), sa)
        currline += 1
        time.sleep(1)

I am no python pro and cant figure out the problem :(


Solution

  • 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 get_line function.

    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 fo.seek(0) call.