Learn to use Socket To create TCP The server , But then everything has to be done from scratch , Sometimes it is more troublesome to use , If you go one step further , It's to provide a little easier to use TCP The server , So much the better . therefore Python The standard library of , It also provides such a function , It's in the module socketserver Inside .
because socketserver In the package , If you don't know how it's used , There's no way to start , Even if it works well , It's also the boatman who finds the plough doesn't make . As a software developer , At this time, we should not be afraid of the spirit of laziness , Step by step forward , You'll always learn . Create a server object TCPServer after , call serve_forever Function to start a loop event , Can continuously receive requests from clients , Until it's closed . Before the server object is instantiated , An inheritance must be provided BaseRequestHandler Subclasses of classes , Then rewrite handle Method to receive client data , Or send data to the client .
So let's define a MyTCPHandler：
# self.request It means that the client is connected in TCP Connect .
self.data = self.request.recv(1024).strip()