Socketserver
The socketserver
module simplifies the task of writing network servers.
There is four basic concrete server classes:
-
CLASS 
socketserver.
tcpserver
server_address , requesthandlerclass , bind_and_ Activate=true
-
This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server. if bind_and_activate is True, the constructor automatically attempts to Invoke server_bind ()
andserver_activate ()
. The other parameters is passed to The Baseserver
base class.
-
CLASS 
socketserver.
udpserver
server_address , requesthandlerclass , bind_and_ Activate=true
-
This uses datagrams, which is discre TE packets of information that is arrive out of order or is lost while in transit. The parameters is the same as For tcpserver< /span>
.
-
-
socketserver.
class UnixStreamServer
(server_address, requesthandlerclass, bind_and_activate=true)
-
-
socketserver.
class UnixDatagramServer
(server_address, requesthandlerclass,bind_and_activate=true)
-
-
These more infrequently used classes is similar to the TCP and UDP classes, but use Unix domain sockets; they ' re Not available on Non-unix platforms. The parameters is the same as For tcpserver< /span>
.
These four classes process requests synchronously; Each request must is completed before the next request can be started. This isn ' t suitable if each request takes a long time to complete, because it requires a lot of computation, or because it Returns a lot of data which the client was slow to process. The solution is to create a separate process or thread to handle each request; The ForkingMixIn
and ThreadingMixIn
mix-in classes can be used to support asynchronous behaviour.
There is five classes in a inheritance diagram, four of the which represent synchronous servers of four types:
+------------+| baseserver | +------------+ | v+-----------+ +------------------+| tcpserver |------->| unixstreamserver | +-----------+ +------------------+ | v+-----------+ +--------------------+| udpserver |------->| unixdatagramserver | +-----------+ +--------------------+
Note UnixDatagramServer
that derives from UDPServer
, not from UnixStreamServer
-the only difference between an IP and a Unix stream server is the add Ress family, which is simply repeated in both Unix server classes.
-
-
Class
socketserver.
ForkingMixIn
-
-
Class
socketserver.
ThreadingMixIn
-
-
Forking and threading versions of each type of the server can be created using these mix-in classes. For instance, is ThreadingUDPServer
created as follows:
Threadingudpserver(threadingmixinudpserverpass
The Mix-in class comes first, since it overrides a method defined in UDPServer
. Setting the various attributes also changes the behavior of the underlying server mechanism.
-
-
Class
socketserver.
ForkingTCPServer
-
-
Class
socketserver.
ForkingUDPServer
-
-
Class
socketserver.
ThreadingTCPServer
-
-
Class
socketserver.
ThreadingUDPServer
-
These classes is pre-defined using the mix-in classes.
Request Handler Objects
class
socketserver.
BaseRequestHandler
This is the superclass of all request handler objects. It defines the interface, given below. A concrete request handler subclass must define a new handle()
method, and can override any of the other methods. A new instance of the subclass is created for each request.
-
setup
()
-
Called before the handle()
method to perform any initialization actions required. The default implementation does nothing.
-
-
handle
()
-
This function must does all the work required to service a request. The default implementation does nothing. Several instance attributes is available to it; The request is available As self.request
; The client address As self.client_address
; And the server instance As self.server
, in case it needs access to per-server information.
The type of is self.request
different for datagram or stream services. For stream services, was self.request
a socket object; For datagram services, is self.request
a pair of string and socket.
-
-
finish
()
-
Called after the handle()
method to perform any clean-up actions required. The default implementation does nothing. If setup()
raises an exception, the This function is not being called.
Server Side
1 ImportSocketserver2 3 classMytcphandler (socketserver. Baserequesthandler):4 """5 The request handler class for our server.6 7 It is instantiated once per connection to the server, and must8 override the handle () method to implement communication to the9 client.Ten """ One A defhandle (self): - #Self.request is the TCP socket connected to the client -Self.data = SELF.REQUEST.RECV (1024). Strip () the Print("{} wrote:". Format (Self.client_address[0])) - Print(Self.data) - #just send back the same data, but upper-cased - Self.request.sendall (Self.data.upper ()) + - if __name__=="__main__": +HOST, PORT ="localhost", 9999 A at #Create the server, binding to localhost on port 9999 -Server =Socketserver. TCPServer (HOST, PORT), Mytcphandler) - - #Activate the server; this would keep running until you - #Interrupt The program with CTRL-C -Server.serve_forever ()
Client Side
1 ImportSocket2 ImportSYS3 4HOST, PORT ="localhost", 99995data =" ". Join (Sys.argv[1:])6 7 #Create a socket (sock_stream means a TCP socket)8Sock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)9 Ten Try: One #Connect to server and send data A Sock.connect ((HOST, PORT)) -Sock.sendall (bytes (data +"\ n","Utf-8")) - the #Receive data from the server and shut down -Received = STR (SOCK.RECV (1024),"Utf-8") - finally: - sock.close () + - Print("Sent: {}". Format (data) + Print("Received: {}". Format (Received))
View Code
The above example you will find that still can not achieve multiple concurrency, haha, the server side to make a change on it
Put
1 |
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) |
Change into
1 |
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) |
Python Network Programming--socketserver Basics