Home  >  Article  >  Backend Development  >  Use Python's SocketServer framework to write network service programs

Use Python's SocketServer framework to write network service programs

高洛峰
高洛峰Original
2016-10-19 16:08:031207browse

1. Foreword:

Although it is convenient to write simple network programs in Python, it is better to use ready-made frameworks for more complex network programs. This allows you to focus on the transaction logic rather than the various details of the socket. The SocketServer module simplifies the task of writing network service programs. At the same time, the SocketServer module is also the basis for many server frameworks in the Python standard library.

2. Network service class:

SocketServer provides 4 basic service classes:

TCPServer for TCP socket streams

UDPServer for UDP datagram sockets

UnixStreamServer and UnixDatagramServer for UNIX domain sockets ,uncommonly used.

Their inheritance relationship is as follows:

+----------------+

| BaseServer |

+----------------+

|

v

+-----------+ +------------------+

| TCPServer |------->| UnixStreamServer |

+-----------+ +------------------+

|

v

+---- -------+ +--------------------+

| UDPServer |------->| UnixDatagramServer |

+- ----------+ +------------------------+

2.1 Asynchronous processing:

These four service classes are all processed synchronously Requested. The next request cannot be processed until one request is processed. To support the asynchronous model, you can use multiple inheritance to let the server class inherit ForkingMixIn or ThreadingMixIn mix-in classes.

ForkingMixIn utilizes multi-process (forking) to achieve asynchronous implementation.

ThreadingMixIn uses multi-threading to achieve asynchronous.

3. Request processing class:

To implement a service, you must also derive a handler class request processing class and override the handle() method of the parent class. The handle method is used specifically to handle requests. This module handles requests through a combination of service classes and request processing classes.

The request processing classes provided by the SocketServer module include BaseRequestHandler, and its derived classes StreamRequestHandler and DatagramRequestHandler. As can be seen from the name, one can handle streaming sockets and the other can handle datagram sockets.

4. Summarize the steps to create a service using SocketServer:

1. Create a request handler class (request processing class), inherit from the BaseRequestHandler class and override its handle() method, which will handle the request.

2. Instantiate a server class object and pass it the address of the service and the previously created request handler class.

3. Call the handle_request() or serve_forever() method of the server class object to start processing the request.

An example of a server based on SocketServer:

from SocketServer import TCPServer,StreamRequestHandler
#定义请求处理类
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print 'Got connection from ',addr
self.wfile.write('Thank you for connecting')
server = TCPServer(('',1234), handler)#实例化服务类对象
server.server_forever()#开启服务

5. Implement asynchronously and support multiple connections

As mentioned when introducing service classes earlier, the four basic service classes are synchronous models by default. To support asynchrony, you can use multiple inheritance to inherit from the ForkingMixIn or ThreadingMixInmix-in classes and a basic service class to define a service class that supports asynchrony. For example:

class Server(ThreadingMixIn, TCPServer): pass

ForkingMixIn Inter-process communication should be considered. ThreadingMixIn should consider synchronization and mutual exclusion when threads access the same variable.

A server example using multi-threading:

from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler
#定义支持多线程的服务类,注意是多继承
class Server(ThreadingMixIn, TCPServer): pass
#定义请求处理类
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print 'Got connection from ',addr
self.wfile.write('Thank you for connection')
server = Server(('', 1234), Handler)#实例化服务类
server.serve_forever()#开启服务


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn