Examples and Tutorials of SocketServer?

John E. Barham jbarham at jbarham.com
Sun Dec 14 02:44:00 CET 2003

Paul Rubin wrote:
> Milo K. Piffenpauffer writes:
> > I've looked on Google for examples of using the SocketServer module,
> > but I'm not having much luck. The online documentation is pretty
> > sparse, and PyDoc isn't very clear. Does anyone know where I could
> > find an example of SocketServer that explains what the various
> > features of the code do?
> "Use the source, Luke".

Ditto.  Admittedly it can be confusing figuring out which of the methods you
need to override.

Here's a slightly edited minimal echo server from the printed Python
Cookbook (i.e., I couldn't find it in the Cookbook on the ActiveState

import SocketServer

class EchoHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        while 1:
            data = self.request.recv(1024)
            if not data: break

EchoServer = SocketServer.TCPServer(("", 8881), EchoHandler)

Run the above and see it in action by doing "telnet localhost 8881" and
typing away.  The characters you type should be repeated (i.e., echoed).  At
least that's what happens for me on XP...

Note that you don't even have to derive your server from one in
SocketServer.  All you have to do minimally is sub-class the
BaseRequestHandler class and override the handle() method.

Note too that the standard library's SimpleHTTPServer is based on
SocketServer.TCPServer (via HTTPServer in BaseHTTPServer) so it's a good,
albeit more complex, example of a SocketServer server.

But at some point you should read and try to trace the source to
SocketServer.  Really, it's not that complicated.


More information about the Python-list mailing list