Search code examples
pythonsocketserver

Reading all waiting lines in a SocketServer handler


This is a simple socketserver example that should receive a line over UDP and echo it out:

import socketserver

class LineHandler(socketserver.DatagramRequestHandler):
    def handle(self):
        line = self.rfile.readline().strip()
        print(line)

server = socketserver.UDPServer(('', 4444), LineHandler)
server.serve_forever()

However if two lines come in at the same time, only the first line is read:

(printf 'lol\n'; printf 'what\n') | nc -u localhost 4444

Solution

  • The documentation kind of suggests that readline() will repeatedly call recv() until it gets a newline, which would leave the next line in the socket's buffer and lead to handle() being invoked again. But this doesn't appear to be the case.

    Instead, you can use:

    for line in self.rfile:
        line = line.strip()
        print(line)