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:

4 Comments:

Blogger Ciantic said...

The idea is good, but I wish there were a Python client example too.

I have similar ways to learn, by simple examples, so now I have to find myself the client example.

November 7, 2007 at 5:08 PM  
Blogger Jens said...

Thanks! I've been looking for an example during the last half an hour and you saved me!

July 10, 2008 at 12:00 PM  
Blogger Unknown said...

Hi, thank you so much.

About a python client you can use something like that:

import socket

sock = socket.socket(socket.AF_INET, sock.SOCK_STREAM)

sock.connect(('localhost', 5000))

print sock.recv(1024)

sock.send('bye')

April 8, 2009 at 1:33 PM  
Blogger Leon said...

Thank you, it is useful to me.

July 21, 2010 at 12:58 AM  

Post a Comment

<< Home