python基础2-socket进阶socketserver

1

First, you must create a request handler class by subclassing the BaseRequestHandlerclass and overriding its handle() method; this method will process incoming requests.   
你必须自己创建一个请求处理类,并且这个类要继承BaseRequireHandlerclass,并且还要重写父类里的handle()
Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class.
你必须实例化TCPServer,并且传递server ip 和你上面创建的请求处理类,给这个TCPSserver
Then call the handle_request() orserve_forever() method of the server object to process one or many requests.

server.Handle_request #只处理一个请求
server.serve_forever() #处理多个请求,永远执行 的server
Finally, call server_close() to close the socket.

 

实例1:

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.
    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """
    def handle(self):   #handle自己处理和客户端所有的交互
        # self.request is the TCP socket connected to the client
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                print("{} wrote:".format(self.client_address[0]))
                print(self.data)
                # if not self.data:    #客户端断开
                #     print(self.client_address,'断开啦')
                #     break
                self.request.send(self.data.upper())
            except ConnectionResetError as e:
                print("error",e)
                break
if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    # server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)    #多线程
    server.serve_forever()
socketserver_1.py
import os
import socket
client = socket.socket() #声明socket类型,同时生成socket连接对象
# client.connect(("localhost",6969))
client.connect(("localhost",9999))

while True:
    msg = input(">>:").strip()
    if len(msg) ==  0:
        continue
    #在py2中是raw_input
    client.send(msg.encode("utf-8"))
    data = client.recv(1024)
    # print("recv:",data.decode())
    print(data)
client.close()
client.py

注:代码内有多线程,取消注释即可

 

class socketserver.BaseServer(server_addressRequestHandlerClass) 主要有以下方法

class socketserver.BaseServer(server_address, RequestHandlerClass)
This is the superclass of all Server objects in the module. It defines the interface, given below, but does not implement most of the methods, which is done in subclasses. The two parameters are stored in the respective server_address and RequestHandlerClass attributes.

fileno()  #返回文件描述符
Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process.

handle_request()  #处理单个请求
Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return.

serve_forever(poll_interval=0.5)   #
Handle requests until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(), which may be used by a subclass or mixin to provide actions specific to a given service. For example, the ForkingMixIn class uses service_actions() to clean up zombie child processes.

Changed in version 3.3: Added service_actions call to the serve_forever method.

service_actions()      #
This is called in the serve_forever() loop. This method can be overridden by subclasses or mixin classes to perform actions specific to a given service, such as cleanup actions.

New in version 3.3.

shutdown()       #
Tell the serve_forever() loop to stop and wait until it does.

server_close()      #
Clean up the server. May be overridden.

address_family      #地址簇
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.

RequestHandlerClass     #请求处理类
The user-provided request handler class; an instance of this class is created for each request.

server_address
The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example.

socket
The socket object on which the server will listen for incoming requests.

The server classes support the following class variables:

allow_reuse_address        #允许重用地址
Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.
###注:在普通的socket上是:
# server = socket.socket() #获取socket实例
# server.setsockopt(socket.SQL_SOCKET,socket.S0_REUSEADDR,1)

request_queue_size
The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses.

socket_type
The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values.

timeout
Timeout duration, measured in seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method is called.

There are various server methods that can be overridden by subclasses of base server classes like TCPServer; these methods aren’t useful to external users of the server object.

finish_request()
Actually processes the request by instantiating RequestHandlerClass and calling its handle() method.

get_request()
Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address.

handle_error(request, client_address)
This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard output and continue handling further requests.

handle_timeout()
This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing.

process_request(request, client_address)     #单个请求的
Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this.

server_activate()
Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden.

server_bind()
Called by the server’s constructor to bind the socket to the desired address. May be overridden.

verify_request(request, client_address)     #判断一个请求是否合法,必须返回一个布尔值
Must return a Boolean value; if the value is True, the request will be processed, and if it’s False, the request will be denied. This function can be overridden to implement access controls for a server. The default implementation always returns True.
View Code

 

posted @ 2017-10-04 15:57  larlly  阅读(374)  评论(0)    收藏  举报