This article mainly introduces the use of Python to implement a simple multithreaded TCP server tutorial, the example of the operating environment for the Windows operating system, the need for friends can refer to the
Recently read "Python core programming", the book implemented a simple 1 to 1 of the tcpserver, but in the actual use of 1 to 1 of the situation is obviously not, so the study of how to start a different thread (process) on the server side to implement each link one thread.
In fact, Python in the design of the class has taken into account the needs of this aspect, we only have to inherit the Socketserver.baserequesthandler on their own server.
The server-side code is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13-14 |
#!/usr/bin/env python import socketserver from time import ctime HOST = ' PORT = 21567 ADDR = (HOST, PORT) class Myreques Thandler (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 (basic and identical in the book, except that the closing link in the loop is commented out):
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18 |
#!/usr/bin/env python from socket import * host = ' localhost ' PORT = 21567 Bufsiz = 1024 ADDR = (HOST, PORT) while True:t Cpclisock = socket (af_inet, Sock_stream) tcpclisock.connect (ADDR) data = Raw_input (' > ') if not data:break tcpclisock. Send ('%SRN '% data) data = TCPCLISOCK.RECV (bufsiz) if not data:break print Data.strip () #tcpCliSock. Close () |
You can see from the client's code that each input creates a new request.
Test, after starting server and client, enter the test in client: