socketserver.py

来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 577 行 · 第 1/2 页

PY
577
字号
"""Generic socket server classes.This module tries to capture the various aspects of defining a server:For socket-based servers:- address family:        - AF_INET{,6}: IP (Internet Protocol) sockets (default)        - AF_UNIX: Unix domain sockets        - others, e.g. AF_DECNET are conceivable (see <socket.h>- socket type:        - SOCK_STREAM (reliable stream, e.g. TCP)        - SOCK_DGRAM (datagrams, e.g. UDP)For request-based servers (including socket-based):- client address verification before further looking at the request        (This is actually a hook for any processing that needs to look         at the request before anything else, e.g. logging)- how to handle multiple requests:        - synchronous (one request is handled at a time)        - forking (each request is handled by a new process)        - threading (each request is handled by a new thread)The classes in this module favor the server type that is simplest towrite: a synchronous TCP/IP server.  This is bad class design, butsave some typing.  (There's also the issue that a deep class hierarchyslows down method lookups.)There are five classes in an inheritance diagram, four of which representsynchronous servers of four types:        +------------+        | BaseServer |        +------------+              |              v        +-----------+        +------------------+        | TCPServer |------->| UnixStreamServer |        +-----------+        +------------------+              |              v        +-----------+        +--------------------+        | UDPServer |------->| UnixDatagramServer |        +-----------+        +--------------------+Note that UnixDatagramServer derives from UDPServer, not fromUnixStreamServer -- the only difference between an IP and a Unixstream server is the address family, which is simply repeated in bothunix server classes.Forking and threading versions of each type of server can be createdusing the ForkingServer and ThreadingServer mix-in classes.  Forinstance, a threading UDP server class is created as follows:        class ThreadingUDPServer(ThreadingMixIn, UDPServer): passThe Mix-in class must come first, since it overrides a method definedin UDPServer!To implement a service, you must derive a class fromBaseRequestHandler and redefine its handle() method.  You can then runvarious versions of the service by combining one of the server classeswith your request handler class.The request handler class must be different for datagram or streamservices.  This can be hidden by using the mix-in request handlerclasses StreamRequestHandler or DatagramRequestHandler.Of course, you still have to use your head!For instance, it makes no sense to use a forking server if the servicecontains state in memory that can be modified by requests (since themodifications in the child process would never reach the initial statekept in the parent process and passed to each child).  In this case,you can use a threading server, but you will probably have to uselocks to avoid two requests that come in nearly simultaneous to applyconflicting changes to the server state.On the other hand, if you are building e.g. an HTTP server, where alldata is stored externally (e.g. in the file system), a synchronousclass will essentially render the service "deaf" while one request isbeing handled -- which may be for a very long time if a client is slowto reqd all the data it has requested.  Here a threading or forkingserver is appropriate.In some cases, it may be appropriate to process part of a requestsynchronously, but to finish processing in a forked child depending onthe request data.  This can be implemented by using a synchronousserver and doing an explicit fork in the request handler classhandle() method.Another approach to handling multiple simultaneous requests in anenvironment that supports neither threads nor fork (or where these aretoo expensive or inappropriate for the service) is to maintain anexplicit table of partially finished requests and to use select() todecide which request to work on next (or whether to handle a newincoming request).  This is particularly important for stream serviceswhere each client can potentially be connected for a long time (ifthreads or subprocesses cannot be used).Future work:- Standard classes for Sun RPC (which uses either UDP or TCP)- Standard mix-in classes to implement various authentication  and encryption schemes- Standard framework for select-based multiplexingXXX Open problems:- What to do with out-of-band data?BaseServer:- split generic "request" functionality out into BaseServer class.  Copyright (C) 2000  Luke Kenneth Casson Leighton <lkcl@samba.org>  example: read entries from a SQL database (requires overriding  get_request() to return a table entry from the database).  entry is processed by a RequestHandlerClass."""# Author of the BaseServer patch: Luke Kenneth Casson Leighton# XXX Warning!# There is a test suite for this module, but it cannot be run by the# standard regression test.# To run it manually, run Lib/test/test_socketserver.py.__version__ = "0.4"import socketimport sysimport os__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",           "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",           "StreamRequestHandler","DatagramRequestHandler",           "ThreadingMixIn", "ForkingMixIn"]if hasattr(socket, "AF_UNIX"):    __all__.extend(["UnixStreamServer","UnixDatagramServer",                    "ThreadingUnixStreamServer",                    "ThreadingUnixDatagramServer"])class BaseServer:    """Base class for server classes.    Methods for the caller:    - __init__(server_address, RequestHandlerClass)    - serve_forever()    - handle_request()  # if you do not use serve_forever()    - fileno() -> int   # for select()    Methods that may be overridden:    - server_bind()    - server_activate()    - get_request() -> request, client_address    - verify_request(request, client_address)    - server_close()    - process_request(request, client_address)    - close_request(request)    - handle_error()    Methods for derived classes:    - finish_request(request, client_address)    Class variables that may be overridden by derived classes or    instances:    - address_family    - socket_type    - reuse_address    Instance variables:    - RequestHandlerClass    - socket    """    def __init__(self, server_address, RequestHandlerClass):        """Constructor.  May be extended, do not override."""        self.server_address = server_address        self.RequestHandlerClass = RequestHandlerClass    def server_activate(self):        """Called by constructor to activate the server.        May be overridden.        """        pass    def serve_forever(self):        """Handle one request at a time until doomsday."""        while 1:            self.handle_request()    # The distinction between handling, getting, processing and    # finishing a request is fairly arbitrary.  Remember:    #    # - handle_request() is the top-level call.  It calls    #   get_request(), verify_request() and process_request()    # - get_request() is different for stream or datagram sockets    # - process_request() is the place that may fork a new process    #   or create a new thread to finish the request    # - finish_request() instantiates the request handler class;    #   this constructor will handle the request all by itself    def handle_request(self):        """Handle one request, possibly blocking."""        try:            request, client_address = self.get_request()        except socket.error:            return        if self.verify_request(request, client_address):            try:                self.process_request(request, client_address)            except:                self.handle_error(request, client_address)                self.close_request(request)    def verify_request(self, request, client_address):        """Verify the request.  May be overridden.        Return true if we should proceed with this request.        """        return 1    def process_request(self, request, client_address):        """Call finish_request.        Overridden by ForkingMixIn and ThreadingMixIn.        """        self.finish_request(request, client_address)        self.close_request(request)    def server_close(self):        """Called to clean-up the server.        May be overridden.        """        pass    def finish_request(self, request, client_address):        """Finish one request by instantiating RequestHandlerClass."""        self.RequestHandlerClass(request, client_address, self)    def close_request(self, request):        """Called to clean up an individual request."""        pass    def handle_error(self, request, client_address):        """Handle an error gracefully.  May be overridden.        The default is to print a traceback and continue.        """        print '-'*40        print 'Exception happened during processing of request from',        print client_address        import traceback        traceback.print_exc() # XXX But this goes to stderr!        print '-'*40class TCPServer(BaseServer):    """Base class for various socket-based server classes.    Defaults to synchronous IP stream (i.e., TCP).    Methods for the caller:    - __init__(server_address, RequestHandlerClass)    - serve_forever()    - handle_request()  # if you don't use serve_forever()    - fileno() -> int   # for select()    Methods that may be overridden:    - server_bind()    - server_activate()

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?