Python之高级库socketserver

socket并不能多并发,只能支持一个用户,socketserver简化了编写网络服务程序的任务,socketserver是socket的在封装。socketserver在python2中为Sock

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

全栈程序员社区此处内容已经被作者隐藏,请输入验证码查看内容
验证码:
请关注本站微信公众号,回复“验证码”,获取验证码。在微信里搜索“全栈程序员社区”或者“www_javaforall_cn”或者微信扫描右侧二维码都可以关注本站微信公众号。

  socket并不能多并发,只能支持一个用户,socketserver 简化了编写网络服务程序的任务,socketserver是socket的在封装。socketserver在python2中为SocketServer,在python3种取消了首字母大写,改名为socketserver。socketserver中包含了两种类,一种为服务类(server class),一种为请求处理类(request handle class)。前者提供了许多方法:像绑定,监听,运行…… (也就是建立连接的过程) 后者则专注于如何处理用户所发送的数据(也就是事务逻辑)。一般情况下,所有的服务,都是先建立连接,也就是建立一个服务类的实例,然后开始处理用户请求,也就是建立一个请求处理类的实例。

1. Python之socketserver架构

  Python之高级库socketserver

2. 如何创建一个socketserver 

(1)创建一个请求处理的类,并且这个类要继承BaseRequestHandler,并且还要重写父类里handle()方法;
(2)你必须实例化 TCPServer,并且传递server IP和你上面创建的请求处理类,给这个TCPServer;
(3)server.handle_requese()#只处理一个请求,server.server_forever()处理多个一个请求,永远执行
(4)关闭连接server_close()

示例:SocketServer.py

#coding:UTF-8

''' socketserver模块实例 '''

import socket
import socketserver

hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
ip_port = (ip, 1122)

class Myhandler(socketserver.BaseRequestHandler):
    def handle(self):
        print (ip_port)
        print (self.request, self.client_address, self.server)
        while True:
            data = self.request.recv(1024)
            print (len(data))
            if len(data) > 0:
                print (data, self.client_address)
                data1 = data.decode("utf8").lower()
                print (data1)
                if data1 == "exit":
                    print ("server exit")
                    break

if __name__ == "__main__":   
    s =socketserver.ThreadingTCPServer((ip_port),Myhandler)
    print (s)
    s.serve_forever()

3. socketserver源码分析

  (1) socketserver工作流程

  擦模考博客:https://blog.csdn.net/qq_33733970/article/details/79153938

  在此感谢Quincy379的精彩分析

(2)class socketserver.BaseServer(server_address, RequestHandlerClass) 主要有以下方法:

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)  
#每0.5秒检查下是否发了shutdown信号,做一些清理工作
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()
#python3.3里加入,

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
#IP地址

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  
#准许重用地址,
普通的socket重用地址
Python之高级库socketserver

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

 
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.

 
Python之高级库socketserver
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.
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/120221.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • python基础(7)内置函数divmod用法

    python基础(7)内置函数divmod用法前言我们都知道,python中//代表整数运算中的取整,%代表整数运算中的取余,那么有什么函数可以同时取到整数和余数吗?答案是有的,使用python内置函数divmoddivmod首先看一下源

    2022年8月7日
    5
  • GMT时间格式转换(Mon Feb 13 08:00:00 GMT+08:00 2012)

    GMT时间格式转换(Mon Feb 13 08:00:00 GMT+08:00 2012)普通的时间转换问题我这里就不再罗嗦了 我想大家应该都会那种低级的转换问题吧 现在我向大家总结一下如何转换 GMT 时间格式 这种格式的转换方法网上还不是很多 所以有必要总结一下 也算给有需要的朋友一个小小的帮助啦 首先先来了解一下 GMT 的时间格式 MonFeb1308 00 00GMT 08 002012 可能还会有其他的格式类似 SunSep0 00 00G

    2025年6月14日
    3
  • AArch64教程第一章

    AArch64教程第一章AArch64教程第一章AArch64是一个新的64位模式,它是ARMv8架构下的一部分,它于2011年随着ARM发布。它被逐步部署于智能手机和服务器。所以我认为现在学习一点关于此架构的知识是比较好的。硬件目前,有ARMv6/ARMv7的单板电脑是比较容易获得的,其中最流行的一个选择是树莓派。相反,支持64位ARMv8模式的单板电脑就没有那么多了,但是它们最近也慢慢变得流行了起来。例如,Pine64,ODROID-C2,Dragonboard410c,等等。它们中的任何一种都可以做64位开发,

    2022年10月16日
    3
  • js获取并设置<p></p>的显示的值。

    js获取并设置<p></p>的显示的值。

    2021年12月9日
    50
  • 博客帮助文档

    博客帮助文档博客积分规则博客等级C币规则(试运营)博客VIP说明(试运营)博客专家如何成为博客专家企业博客如何开通企业博客博客勋章分类专栏博客搬家自定义百度统计CSDN博客用户准则Markdown帮助博客积分规则博客积分是CSDN对用户努力的认可和奖励,也是衡量博客水平的重要标准。博客等级也将由博客积分唯一决定。积分规则具体如下:1、每发布一篇…

    2022年5月1日
    80
  • TCP-RST_tcp快速重传为什么是三次

    TCP-RST_tcp快速重传为什么是三次        在谈RST攻击前,必须先了解TCP:如何通过三次握手建立TCP连接、四次握手怎样把全双工的连接关闭掉、滑动窗口是怎么传输数据的、TCP的flag标志位里RST在哪些情况下出现。下面我会画一些尽量简化的图来表达清楚上述几点,之后再了解下RST攻击是怎么回事。1、TCP是什么?TCP是在IP网络层之上的传输层协议,用于提供port到port面向连接的可靠…

    2022年10月1日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号