The SocketServer module in Python is used to process network requests.

Source: Internet
Author: User

The SocketServer module in Python is used to process network requests.

SocketServer creates a network service framework. It defines classes to process synchronous network requests on TCP, UDP, UNIX streams, and UNIX worker rams.

I. Server Types

There are five different server classes in SocketServer.

1. BaseServer defines the API, and it is not used for instantiation and direct use.
2. TCPServer is used for socket communication of TCP/IP.
3. UDPServer uses datatesockets.
4. UnixStreamServer and unixw.ramserver use Unix-domain sockets and use it intelligently on unix platforms.

Ii. Server Objects

Build a server to listen to the request address and request processing class (not instance ).

1. class SocketServer. BaseServer
This is the superclass of all server objects in the module. It defines interfaces and most implementations are completed in subclasses.

2. BaseServer. fileno

Returns an integer file descriptor to indicate which server is listening. This function is most commonly passed to select. select (), allowing monitoring of multiple services with the same processing process.

3. BaseServer. handle_request

To process a single request, this function calls the following methods in sequence. Get_request (), verify_request, and proccess_request.
If the handle () method provided by the user throws an exception, the handle_error () method will be called.
If no request is received within the time of self. timeout, handle_timeout () and handle_request () will be returned.

4. BaseServer. serve_forever

BaseServer. serve_forever (poll_interval = 0.5), which processes the request until the explicit shutdown () request. The rotation is disabled every poll_interval. Ignore self. timeout. If you need to use a scheduled task, you need to use other threads.

5. BaseServer. shutdown

Tells serve_forever () to stop the loop.

6. BaseServer. RequestHandlerClass

The user request processing program class creates an instance of this class for each request.

Iii. Implementing a Server

If you create a server, it can usually reuse existing classes and simply provide a class for custom request processing. If not, several BaseServer Methods overwrite one subclass.

1. verify_request (reqeust, client_address): A boolean value must be returned. If True is returned, the request will be processed. If False is returned, the request will be rejected. This function can be overwritten to implement the access control service.
2. process_request (request, client_address): Call finish_request to create a RequestHandlerClass () instance. If you need this function, you can create a new process or coroutine to process the request.
3. finish_request (request, client_address): Creates a request processing instance. Call handle () to process the request.

4. Request Handlers

Most of the work done by the request handler receives incoming requests and determines what action to take. The handler is responsible for implementing the Socket Layer (for example, HTTP or xml-rpc) on the "protocol ). Read the request data channel, process, and write a response from the input request processing program. Three methods can be rewritten.

1. setup (): The request processing program to prepare the request is to initialize and run before handle.
2. handle (): do real request work. Parse incoming requests to process data and return responses.
3. finish (): Clear setup () created at any time ().

V. Example

The following example shows tcp, udp, and asynchronous

1. TCPServer example

import SocketServerclass MyHandler(SocketServer.BaseRequestHandler):    def handle(self):    self.data = self.request.recv(1024).strip()    print '{} wrote:'.format(self.client_address[0])    print self.data    self.request.sendall(self.data.upper())if __name__ == '__main__':  HOST, PORT = 'localhost', 9999  server = SocketServer.TCPServer((HOST, PORT), MyHandler)  server.serve_forever()

2. UDPServr example

import SocketServerclass MyHandler(SocketServer.BaseRequestHandler):  def handle(self):    data = self.request[0].strip()    socket = self.request[1]    print '{} wrote:'.format(self.client_address[0])    print data    socket.sendto(data.upper(), self.client_address)if __name__ == '__main__':  HOST, PORT = 'localhost', 9999  server = SocketServer.UDPServer((HOST, PORT), MyHandler)  server.serve_forever()

3. asynchronous example

The ThreadingMixIn and ForkingMixIn classes can be used to construct asynchronous processing programs.

import socketimport threadingimport SocketServerclass MyHandler(SocketServer.BaseRequestHandler):  def handle(self):    data = self.request.recv(1024)    curr_thread = threading.current_thread()    response = '{}: {}'.format(curr_thread.name, data)    self.request.sendall(response)class Server(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 'Received: {}'.format(response)  finally:    sock.close()if __name__ == '__main__':  HOST, PORT = 'localhost', 0  server = Server((HOST, PORT), MyHandler)  ip, port = server.server_address  serer_thread = threading.Thread(target=server.serve_forever)  server_thread.daemon = True  server_thread.start()  print 'Server loop running in thread:', server_thread.name  client(ip, port, 'Hello World 1')  client(ip, port, 'Hello World 2')  client(ip, port, 'Hello World 3')  server.shutdown()  server.server_close()

4. SocketServer implements non-blocking communication between the client and server
(1) create a SocketServerTCP Server

# Create a SocketServerTCP server: import SocketServer from SocketServer import StreamRequestHandler as SRH from time import ctime host = 'xxx. xxx. xxx. xxx 'port = 9999 addr = (host, port) class Servers (SRH): def handle (self): print 'got connection from', self. client_address self. wfile. write ('Connection % s: % s at % s succeed! '% (Host, port, ctime () while True: data = self. request. recv (1024) if not data: break print data print "RECV from", self. client_address [0] self. request. send (data) print 'server is running .... 'server = SocketServer. threadingTCPServer (addr, Servers) server. serve_forever ()

(2) create a SocketServerTCP Client

from socket import *  host = 'xxx.xxx.xxx.xxx' port = 9999 bufsize = 1024 addr = (host,port) client = socket(AF_INET,SOCK_STREAM) client.connect(addr) while True:   data = raw_input()   if not data or data=='exit':     break   client.send('%s\r\n' % data)   data = client.recv(bufsize)   if not data:     break   print data.strip() client.close() 

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.