Python tutorials using the Socketserver module to write basic server programs _python

Source: Internet
Author: User
Tags mixed unix domain socket ssl connection in python

Socketserver simplifies the authoring of Web servers. It has 4 classes: Tcpserver,udpserver,unixstreamserver,unixdatagramserver. These 4 classes are processed synchronously, and asynchronous is supported by the Forkingmixin and ThreadingMixIn classes.

Steps to create a server. First, you must create a request processing class, which is a subclass of Baserequesthandler and overloads its handle () method. Second, you must instantiate a server class, the address of the incoming server, and the request handler class. Finally, call Handle_request () (typically call other event loops or use Select ()) or Serve_forever ().

You need to handle an exception shutdown when integrating the ThreadingMixIn class. Daemon_threads indicates whether the server will wait for the thread to terminate, and if the thread is independent of each other, it must be set to True and false by default.

Regardless of the network protocol used, the server class has the same external methods and properties.

In Python3, this module is a socketserver module. In Python 2, this module is the Socketserver module. So when importing with import, you should import it in a separate situation, or you will get an error. The imported code is as follows:

Try:
  import socketserver   #Python 3
except Importerror:
  import socketserver   #Python 2

The Socketserror module includes a number of classes that simplify TCP, UDP, and UNIX domain socket server implementations.

First, Handler
to use this module, you must define a handler class that inherits the base class Baserequesthandler. Instance h of the Baserequesthandler class can implement the following methods:
1, H.handle ()   Call the method to perform the actual request operation. This function can be called without any arguments, but several instance variables contain useful values. H.request contains the request, H.client_address contains the client address, and H.server contains an instance of the calling handler. For data flow services such as TCP, the H.request property is a socket object. For the datagram service, it is a byte string that contains the received data.
2, H.setup ()    the method is called before handle (). By default, it does not perform any action. If you want the server to implement more connection settings, such as establishing an SSL connection, you can do this here.
3, H.finish ()    Call this method to perform a purge after the handle () is executed. By default, it does not perform any action. If both the setup () and handle () methods do not generate an exception, you do not need to invoke the method.
If you know that your application can only manipulate connections that are oriented to data flow (such as TCP), you should inherit from Streamrequesthandler instead of Baserequesthandler. The Streamrequesthandler class sets two properties, H.wfile is the class file object that writes data to the client, H.rfile is a class file object that reads data from the client.
If you want to write a handler for a packet operation and the response continues to return to the sender, it should inherit from Datagramrequesthandler. It provides the same class interface as Stramrequesthandler.

Second, the server
to use a handler, you must insert it into the server object. Four basic server classes are defined.
(1) tcpserver (Address,handler) supports servers that use the IPV4 TCP protocol, and address is a (host,port) tuple. Handler is an instance of a subclass of a baserequesthandler or Streamrequesthandler class.
(2) Udpserver (Address,handler) supports servers using the IPV4 UDP protocol, and address and handler are similar to those in TCPServer.
(3) Unixstreamserver (address,handler) uses UNIX domain sockets to implement a data-flow protocol-oriented server that inherits from TCPServer.
(4) Unixdatagramserver (address,handler) server that uses UNIX domain sockets to implement datagram protocols inherits from Udpserver.
An instance of all four server classes has the following methods and variables:
1, S.socket the socket object used for incoming requests.
2, s.sever_address Monitor the address of the server. such as tuples ("127.0.0.1", 80)
3. S.requesthandlerclass the request handler class that is passed to the server constructor and provided by the user.
4, S.serve_forever () Processing of unlimited requests
5, S.shutdown () stop serve_forever () cycle
6, S.fileno () returns the integer file descriptor for the server socket. This method can effectively use a server instance through a polling operation, such as the Select () function.

Iii. defining a custom server
Servers often require special configurations to handle different network address families, time-out periods, concurrency, and other functions, which can be defined by inheriting the four basic server classes above.
You can get more server functionality through a mixed class, which is also a way to add and distribute through a process or thread branch. To achieve concurrency, the following classes are defined:
(1) Forkingmixin a hybrid method of adding a UNIX process branch to a server that enables servers to serve multiple customers.
(2) ThreadingMixIn modify the server's mixed class, you can use the thread to service multiple clients.
To add these features to the server, you can use multiple inheritance, which lists the mixed classes first.
Because concurrent servers are common, Socketserver defines the following server classes in order to define them:
(1) forkingudpserver (Address,handler)
(2) Forkingtcpserver (Address,handler)
(3) Threadingudpserver (Address,handler)
(4) Threadingtcpserver (Address,handler)
The above is a little messy, now summed up the following:
The classes in the Socketserver module are mainly the following:
1, Baseserver contains the core functions of the server and mixed-Class (mix-in) hook function. This class is primarily used for derivation, do not directly generate class objects of this class, you can consider the use of TCPServer and Udpserver classes.
2, TCPServer Basic network Synchronization TCP Server
3, Udpserver Basic network synchronization UDP server
4. Forkingmixin implements the core process functionality for mixing with server classes (mix-in) to provide some asynchronous features. Do not directly generate objects of this class.
5. ThreadingMixIn implements the core threading functionality for mixing with server classes (mix-in) to provide some asynchronous features. Do not directly generate objects of this class.
6, the combination of Forkingtcpserver forkingmixin and TCPServer
7, the combination of Forkingudpserver forkingmixin and Udpserver
8, Baserequesthandler
9. A implementation of Streamrequesthandler TCP request processing class
10. An implementation of Datastreamrequesthandler UDP request processing class
Now the complex transactions have been encapsulated into the class, the direct use of the class can be.

Iv. examples
1. TCP Server-side code written using the Socketserver module:

#! /usr/bin/env python
#coding =utf-8 "" "
using Socketserver to implement a simple TCP Server" "from
socketserver import (tcpserver , Streamrequesthandler as SRH) from time
import CTime
class Myrequesthandler (SRH):
  def handle (self):
    Print "Connected from", Self.client_address
    self.wfile.write ("[%s]%s"% (CTime (), Self.rfile.readline ()
) Tcpser=tcpserver (("", 10001), Myrequesthandler)
print "Waiting for Connection"
Tcpser.serve_forever ()
appropriate TCP client code:
#! /usr/bin/env python
#coding =utf-8 from
socket import *
bufsize=1024
#每次都要创建新的连接 while
True :
  tcpclient=socket (Af_inet,sock_stream)
  tcpclient.connect (("localhost", 10001))
  data=raw_input (" > ")
  if not data:
    break
  tcpclient.send ("%s\r\n "%data)
  data1=tcpclient.recv (bufsize)
  If not data1:
    break
  print Data1.strip ()
  tcpclient.close ()

2. Implementation of Asynchronous server

Examples of threadingmixin:

Import Socketimport threadingimport socketserverclass Threadedtcprequesthandler (socketserver.baserequesthandler): def handle (self): data = SELF.REQUEST.RECV (1024) Cur_thread = Threading.current_thread () response = "{}: {}". f Ormat (cur_thread.name, data) Self.request.sendall (response) class Threadedtcpserver (Socketserver.threadingmixin, Socketserver.tcpserver): Passdef Client (IP, port, message): sock = Socket.socket (socket.af_inet, socket. Sock_stream) sock.connect ((IP, port) try:sock.sendall (message) response = SOCK.RECV (1024) print "Receive D: {} '. Format (response) Finally:sock.close () if __name__ = = "__main__": # Port 0 means to select a arbitrary unus Ed Port HOST, port = "localhost", 0 server = Threadedtcpserver ((HOST, Port), Threadedtcprequesthandler) IP, port = Server.server_address # Start a thread with the server--this thread would then Start one # more thread for each reques T server_thread = Threading. Thread (Target=servEr.serve_forever) # Exit The server thread when the main thread terminates Server_thread.daemon = True Server_thread . Start () print "Server loop running in thread:" Server_thread.name client (IP, port, "Hello World 1") Client (IP, PO

 RT, "Hello World 2") client (IP, port, "Hello World 3") Server.shutdown ()

Execution results:

$ python threadedtcpserver.py
Server loop running in thread:thread-1
received:thread-2: Hello World 1
recei Ved:thread-3: Hello World 2
received:thread-4: Hello World 3

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.