python socket-framework 1

  SocketServer 简化了服务器的编写,该模块包含下面四个类TCPServer,UDPServer,UnixStreamServer,UnixDatagramServer,

为使其支持异步,可以使用ForkingMixIn和ThreadingMixIn类。

  python Doc:There are four basic server classes: TCPServer uses the Internet TCPprotocol, which provides for continuous streams

of data between the client and server. UDPServer uses datagrams, which are discrete packets of information that may arrive out of order

or be lost while in transit. The more in frequently used UnixStreamServer and UnixDatagramServer classes are similar, but use

Unix domain sockets; they’re not available onnon-Unix platforms. For more details on network programming, consult a booksuch asW.

Richard Steven’s UNIX Network Programming or Ralph Davis’s Win32 NetworkProgramming.

下面一段doc是关于python支持同步异步的描述,即在server类创建实例中将ForkingMixIn和ThreadingMixIn作为参数传入即可实现异步

 python Doc:These four classes process requests synchronously; each request must becompleted before the next request can be started.

This isn’t suitable if eachrequest takes a long time to complete, because it requires a lot of computation,or because it returns a lot of data

which the client is slow to process. Thesolution is to create a separate process or thread to handle each request; theForkingMixIn and

ThreadingMixIn mix-in classes can be used tosupport asynchronous behaviour.

四个基类支持不同的网络传输协议,在编写服务器时需要实现一个处理类,继承自Base(协议名:)RequestHandler  例如BaseHTTPRequestHandler

 python Doc:Creating a server requires several steps. First, you must create a requesthandler class by subclassing theBaseRequestHandler

class andoverriding its handle() method; this method will process incomingrequests. Second, you must instantiate one of the server classes, passing

itthe server’s address and the request handler class. Finally, call thehandle_request() orserve_forever() method of the server

object toprocess one or many requests.

+------------+
| BaseServer |
+------------+
      |
      v
+-----------+        +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+        +------------------+
      |
      v
+-----------+        +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+        +--------------------+
下面是无multithread的简单例子

#!/usr/bin/env python
from BaseHTTPServer import HTTPServer , BaseHTTPRequestHandler
#import time

#starttime = time.time()


#class RequestHandler 继承自BaseHTTPRequestHandler 并且在最后创建服务器实例的时候作为执行行为参数传入
class RequestHandler(BaseHTTPRequestHandler):
        def _writeheaders(self):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
        
        def do_HEAD(self):
                self._writeheaders()
        
        def do_GET(self):
                self._writeheaders()
                self.wfile.write("""<HTML><HEAD><TITLE>Sample Page</TITLE></HEAD><BODY>this is a sample html page</BODY></HTML>""")

serveraddr = ('', 8765)
srvr = HTTPServer(serveraddr, RequestHandler)
srvr.serve_forever()

下面我们考虑如何让服务器变为异步处理,即引进Mix-In的类,我们只要在代码中加入如下就可以了

#Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer — the only difference between an IP and a 
#Unix stream server is the address family, which is simply repeated in both Unix server classes.

#Forking and threading versions of each type of server can be created using the ForkingMixIn and ThreadingMixIn mix-in 
#classes. For instance, a threading UDP server class is created as follows:

class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass

建议好好看一下下面的文档部分

Python Doc:

The request handler class must define a new handle() method, and canoverride any of the following methods. A new instance is created for eachrequest.

RequestHandler. finish ( )

Called after the handle() method to perform any clean-up actionsrequired. The default implementation does nothing. Ifsetup()raises an exception, this function will not be called.

RequestHandler. handle ( )

This function must do all the work required to service a request. Thedefault implementation does nothing. Several instance attributes areavailable to it; the request is available asself.request; the clientaddress asself.client_address; and the server instance asself.server, in case it needs access to per-server information.

The type of self.request is different for datagram or streamservices. For stream services,self.request is a socket object; fordatagram services,self.request is a pair of string and socket.However, this can be hidden by using the request handler subclassesStreamRequestHandler or DatagramRequestHandler, whichoverride thesetup() andfinish() methods, and provideself.rfile andself.wfile attributes.self.rfile andself.wfile can be read or written, respectively, to get the requestdata or return data to the client.

RequestHandler. setup ( )

Called before the handle() method to perform any initialization actionsrequired. The default implementation does nothing.


lib部分注释(包括可能被重载和被调用,可以看下)

 """Base class for server classes.

    Methods for the caller:

    - __init__(server_address, RequestHandlerClass)
    - serve_forever(poll_interval=0.5)
    - shutdown()
    - 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
    - handle_timeout()
    - verify_request(request, client_address)
    - server_close()
    - process_request(request, client_address)
    - shutdown_request(request)
    - 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:

    - timeout
    - address_family

    - socket_type
    - allow_reuse_address

    Instance variables:

    - RequestHandlerClass
    - socket

    """





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值