Python network programming in----python3.* Socketserver

Source: Internet
Author: User

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
Datagramrequesthandler

Create a SOCKETSERVERTCP server [Python]View PlainCopy
  1. From Socketserver import (TCPServer as TCP, Streamrequesthandler as SRH) #可以通过as起别名
  2. From time import CTime
  3. HOST = ' '
  4. PORT = 1234
  5. ADDR = (HOST, PORT)
  6. Class Myrequesthandler (SRH):
  7. def handle (self):
  8. print (' already connected: ', self.client_address)
  9. self.wfile.write ((' [%s]%s '% (CTime (), self.rfile.readline (). Decode ("UTF-8")). Encode ("UTF-8") ))  
  10. Tcpserv = TCP (ADDR, Myrequesthandler)
  11. Print (' Wait for a new connection .... ')
  12. 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. The Streamrequesthandler class supports operation of input and output sockets like the action file object. We can use the ReadLine () function to get the customer message and send the string to the customer using the write () function.

Create a SOCKETSERVERTCP client [Python]View PlainCopy
  1. #coding =utf-8
  2. From Socket Import *
  3. Import Sys
  4. Reload (SYS)
  5. sys.setdefaultencoding (' UTF8 ')
  6. HOST = ' 192.168.1.27 '
  7. PORT = 1234
  8. BUFSIZE = 1024x768
  9. ADDR = (HOST, PORT)
  10. While True:
  11. Tcpclisock = socket (af_inet, SOCK_STREAM)
  12. Tcpclisock.connect (ADDR)
  13. data = Raw_input (' > ')
  14. if not data:
  15. Break
  16. Tcpclisock.send ('%s\r\n '% data.encode ("UTF-8"))
  17. data = Tcpclisock.recv (BUFSIZE). Decode ("UTF-8")
  18. if not data:
  19. Break
  20. print (Data.strip ())
  21. 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: forks occupy resources, and if there are too many clients forks are not very good fork (even though, for a reasonable number of clients, fork in 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:

[Python]View PlainCopy
  1. From Socketserver import (TCPServer as TCP, Streamrequesthandler as srh,forkingmixin as FMI) #变动位置
  2. From time import CTime
  3. HOST = ' '
  4. PORT = 1234
  5. ADDR = (HOST, PORT)
  6. Class Server (FMI, TCP): #变动位置
  7. Pass
  8. Class Myrequesthandler (SRH):
  9. def handle (self):
  10. print (' already connected: ', self.client_address)
  11. self.wfile.write ((' [%s]%s '% (CTime (), self.rfile.readline (). Decode ("UTF-8")). Encode ("UTF-8") ))  
  12. Tcpserv = Server (ADDR, Myrequesthandler) #变动位置
  13. Print (' Wait for a new connection .... ')
  14. Tcpserv.serve_forever ()

Multithreadingsocketserver Server: [Python]View PlainCopy
  1. From Socketserver import (TCPServer as TCP, Streamrequesthandler as srh,threadingmixin as TMI) #变动位置
  2. From time import CTime
  3. HOST = ' '
  4. PORT = 1234
  5. ADDR = (HOST, PORT)
  6. Class Server (TMI, TCP): #变动位置
  7. Pass
  8. Class Myrequesthandler (SRH):
  9. def handle (self):
  10. print (' already connected: ', self.client_address)
  11. self.wfile.write ((' [%s]%s '% (CTime (), self.rfile.readline (). Decode ("UTF-8")). Encode ("UTF-8") ))  
  12. Tcpserv = Server (ADDR, Myrequesthandler) #变动位置
  13. Print (' Wait for a new connection .... ')
  14. Tcpserv.serve_forever ()

Python network programming in----python3.* Socketserver

Related Article

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.