Introduction
Socketserver (the Socketserver module in python2.*) is a high-level module in the standard library. To simplify the implementation of the network client and server (in the previous process of using the socket, we set the socket type, then call bind (), listen (), accept (), and finally use the while loop to allow the server to continuously accept the request. These steps can be simplified by socketserver packages. )。 module, you have implemented some classes that are available for use.
We will again implement the previous example of the basic TCP. You'll notice that the new implementation has a lot in common with the previous one, but you also have to notice that there are a lot of things that are already wrapped up and you don't have to care about that boilerplate code anymore. The example given is the simplest synchronization server.
In order to hide the details of the implementation. We will now use the class when we write the program, which is different from the previous code. The object-oriented approach helps us to better organize our data and logical functions. You will also notice that our program is now "event driven". This means that the program has a "reaction" only when the event occurs.
In the previous service loop, we blocked the wait request, processed the request when the request came, and then went back to wait. Now in the service loop, you do not have to write code in the server, to define a processor, the server in the incoming request, you can call your handler function.
Class description
Baseserver contains the core functions of the server and the hook function of the hybrid (Mix-in) class. This class is used for derivation and does not directly generate class objects of this class, and you can consider using TCPServer and udpserver.
Tcpserver/udpserver Basic Network Synchronization TCP/UDP Server
unixstreamserver/basic file-based synchronization TCP/UDP server
Unixdatagramserver
Forkingmixin/implements the core process or threading functionality for mixing with server classes (mix-in) to provide some asynchronous features.
ThreadingMixIn do not directly generate objects of this class
Combination of Forkingtcpserver/forkingmixin and tcpserver/udpserver
Forkingudpserver
Combination of Threadingtcpserver/threadingmixin and tcpserver/udpserver
Threadingudpserver
The Baserequesthandler contains core functionality for processing service requests. To derive only new classes, do not directly generate objects of this class, consider using Streamrequesthandler or Datagramrequesthandler
An implementation of the request processing class for the STREAMREQUESTHANDLER/TCP/UDP server
DatagramrequesthandlerCreate a SOCKETSERVERTCP server
From Socketserver import (TCPServer as TCP, Streamrequesthandler as SRH) #可以通过as起别名from time import ctime HOST = "POR T = 1234ADDR = (HOST, PORT) class Myrequesthandler (SRH): def handle (self): print (' already connected: ', self.client_address) Self.wfile.write ((' [%s]%s '% (CTime (), Self.rfile.readline (). Decode ("UTF-8"))). Encode ("UTF-8")) Tcpserv = TCP (ADDR, Myrequesthandler) print (' Wait for a new connection .... ') Tcpserv.serve_forever ()
We derive a subclass from the Streamrequesthandler class of Socketserver and override the handle () function. In the Baserequest class, this function does nothing.The handle () function is called when a client message comes in.。 Streamrequesthandler class Supportmanipulate input and output sockets as you do file objects。 We can useReadLine () function get customer messageUsewrite () functionSend a string to the customer.
Create a SOCKETSERVERTCP client
#coding =utf-8from Socket Import *import sysreload (SYS) sys.setdefaultencoding (' UTF8 ') HOST = ' 192.168.1.27 ' PORT = 1234BUFSIZE = 1024ADDR = (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.encode ("UTF-8")) data = TCPCLISOCK.RECV (BUFSIZE). Decode ("UTF-8") if not data: break print (Data.strip ()) Tcpclisock.close ()
using Socketserver to process multiple links
The above example can only connect to one client at a time and output its request, if you want to handle multiple connectivity problems, then there are three main ways to do this: fork (forking), Thread (threading), and asynchronous I/O (asynchronous I/O). By using the mixed class (Mix-in Class) with the Socketserver server, the derived processes and threads are easily handled. These methods are easy to use, even if you want to implement them yourself. They do have drawbacks:Fork occupies Resources, and if there are too many client forks can not be very good fork (however, for a reasonable number of clients, fork in the modern UNIX or Linux system is very efficient, if there is a multi-CPU system, the system efficiency will be higher);thread processing can cause synchronization problems。 Creating a fork or thread server with the Socketserver framework is straightforward:
Fork Server:
From Socketserver import (TCPServer as TCP, Streamrequesthandler as srh,forkingmixin as FMI) #变动位置from time Import CTI Me HOST = ' Port = 1234ADDR = (HOST, Port) class Server (FMI, TCP): #变动位置 passclass myrequesthandler (SRH): def Handle (self): print (' already connected: ', self.client_address) self.wfile.write ((' [%s]%s '% (CTime (), Self.rfile.readline (). Decode ("UTF-8")). Encode ("UTF-8")) Tcpserv = Server (ADDR, Myrequesthandler) #变动位置print (' Wait for a new connection .... ') Tcpserv.serve_forever ()
MultithreadingSocketserverServer:
From Socketserver import (TCPServer as TCP, Streamrequesthandler as srh,threadingmixin as TMI) #变动位置from time import C Time HOST = ' Port = 1234ADDR = (HOST, Port) class Server (TMI, TCP): #变动位置 passclass myrequesthandler (SRH): de F Handle (self): print (' already connected: ', self.client_address) self.wfile.write ((' [%s]%s '% (CTime (), Self.rfile.readline (). Decode ("UTF-8")). Encode ("UTF-8")) Tcpserv = Server (ADDR, Myrequesthandler) #变动位置print (' Wait for a new connection .... ') Tcpserv.serve_forever ()
Previous: Python network programming----UDP-based python simple server
Next Talk:
If you have any questions, welcome to my public question ~
Python network programming in----python3.* Socketserver