Using Python to implement a simple multi-thread TCP server tutorial, pythontcp
I recently read "python core programming". The book implements a simple one-to-one TCPserver, but in actual use, the one-to-one situation is obviously not good, so I studied how to start different threads (processes) on the server side to implement each link to a thread.
In fact, python has considered this requirement in the class design. We only need to inherit SocketServer. BaseRequestHandler from our own server.
The server code is as follows:
#!/usr/bin/env python import SocketServer from time import ctime HOST = '' PORT = 21567 ADDR = (HOST, PORT) class MyRequestHandler(SocketServer.BaseRequestHandler): def handle(self): print '...connected from:', self.client_address while True: self.request.sendall('[%s] %s' % (ctime(),self.request.recv(1024))) tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler) print 'waiting for connection...' tcpServ.serve_forever()
The client code is as follows (basically the same as in the book, but the closed link in the loop is commented out ):
#!/usr/bin/env python from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) data = raw_input('> ') if not data: break tcpCliSock.send('%s\r\n' % data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data.strip() #tcpCliSock.close()
From the client code, we can see that a new request is created every time a request is entered.
Test. After the server and client are started, enter the test in the client: