Python network programming: basic use of socketserver, pythonsocketserver

Source: Internet
Author: User

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.
      • Server. serve_forever ()
    • Stop server_forever: shutdown ()
      • Server. 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 ()

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.