Python network programming: basic use of socketserver, pythonsocketserver
Content:
- Introduction to socketserver
- Use of socketserver
- Asynchronous Server of socketserver
Start Time:
You can also use socketserver to create a socket
Socketserver introduction:
- Socketserver is an advanced module in the standard library.
- Socketserver simplifies the code for creating a client and a server
Use of socketserver:
- First import module: import socketserver
- Initialize the Controller class Handler. Handler is a handle method in the Handler class that inherits the BaseRequestHandler class, which determines the operation of each connection. [The Class Name of the controller class can be other, not necessarily Handler, as long as BaseRequestHandler is inherited]
-
- Init (): Initialize control settings, initialize connection sockets, addresses, and process instance information.
- Handle (): defines how to process each connection.
- Setup (): Run before handle (). It is generally used to set connection configurations other than the default value.
- Finish (): run the command after handle.
- Variable:
-
- The self. request attribute is a socket object, so self. request. xxxx is used to call the socket function.
- Self. server contains the instance that calls the processing program
- Self. client_address is the client address information.
- Define the server type [pass in the address and port parameters of the Handler class and server ]:
-
- TCPServer supports ipv4 TCP server.
- Server = socketserver. TCPServer (HOST, PORT), Handler) [Handler]
- UDPServer supports ipv4 UDP protocol servers.
- Server = socketserver. UDPServer (HOST, PORT), Handler)
- Run the server
-
- Continuous cyclic Operation: serve_forever (). Even if an error is reported for a connection, the program will not stop, but will continue to run and communicate with other clients.
- Stop server_forever: shutdown ()
Server:
Import socketserverclass MyTCPHandler (socketserver. baseRequestHandler): def handle (self): try: while True: self. data = self. request. recv (1024) print ("{} send :". format (self. client_address), self. data) if not self. data: print ("connection lost") break self. request. sendall (self. data. upper () failed t Exception as e: print (self. client_address, "disconnected") finally: self. request. close () def setup (self): print ("before handle, Connection Established:", self. client_address) def finish (self): print ("finish run after handle") if _ name __= = "_ main _": HOST, PORT = "localhost ", 9999 server = socketserver. TCPServer (HOST, PORT), MyTCPHandler) server. serve_forever ()
Client:
Import socketclient = socket. socket () client. connect ('localhost', 9999) while True: cmd = input ("(quit)> "). strip () if len (cmd) = 0: continue if cmd = "quit": break client. send (cmd. encode () implements _res = client. recv (1024) print (pai_res.decode () client. close ()
Asynchronous Server of socketserver:
Multithreading: ThreadingTCPServer
Multi-process: ForkingTCPServer (Unix)
Multi-threaded edition:
Import socketserverclass MyTCPHandler (socketserver. baseRequestHandler): def handle (self): try: while True: self. data = self. request. recv (1024) print ("{} send :". format (self. client_address), self. data) if not self. data: print ("connection lost") break self. request. sendall (self. data. upper () failed t Exception as e: print (self. client_address, "disconnected") finally: self. request. close () def setup (self): print ("before handle, Connection Established:", self. client_address) def finish (self): print ("finish run after handle") HOST, PORT = "localhost", 9999 server = socketserver. threadingTCPServer (HOST, PORT), MyTCPHandler) # multi-threaded server. serve_forever ()