18 September, 2007

Python SocketServer.ThreadingTCPServer Example

I was surprised to find that SocketServer.ThreadingTCPServer don't have any documentation at all. So after spending some time on Google I finally found a very good example at a forum thread.

I'm posting it here hoping to make it easier for people on the web to find it:
import SocketServer

class EchoRequestHandler(SocketServer.BaseRequestHandler):
    def setup(self):
        print self.client_address, 'connected!'
        self.request.send('hi ' + str(self.client_address) + '\n')

    def handle(self):
        while 1:
            data = self.request.recv(1024)
            self.request.send(data)
            if data.strip() == 'bye':
                return

    def finish(self):
        print self.client_address, 'disconnected!'
        self.request.send('bye ' + str(self.client_address) + '\n')

#server host is a tuple ('host', port)
server = SocketServer.ThreadingTCPServer(('localhost', 5000), EchoRequestHandler)
server.serve_forever()

This is a simple "echo server" which will reply everything you send to him. Send "bye" to close a connection.

Labels: