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:
This is a simple "echo server" which will reply everything you send to him. Send "bye" to close a connection.
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: python
4 Comments:
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.
Thanks! I've been looking for an example during the last half an hour and you saved me!
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')
Thank you, it is useful to me.
Post a Comment
<< Home