Python之高级库socketserver
socket并不能多并发,只能支持一个用户,socketserver 简化了编写网络服务程序的任务,socketserver是socket的在封装。socketserver在python2中为SocketServer,在python3种取消了首字母大写,改名为socketserver。socketserver中包含了两种类,一种为服务类(server class),一种为请求处理类(request handle class)。前者提供了许多方法:像绑定,监听,运行…… (也就是建立连接的过程) 后者则专注于如何处理用户所发送的数据(也就是事务逻辑)。一般情况下,所有的服务,都是先建立连接,也就是建立一个服务类的实例,然后开始处理用户请求,也就是建立一个请求处理类的实例。
1. Python之socketserver架构
2. 如何创建一个socketserver
示例: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) 主要有以下方法:
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.
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.
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.
Changed in version 3.3: Added service_actions call to the serve_forever method.
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.
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.
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:
Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.
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 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.
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.
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) #判断一个请求是否合法
Python之高级库socketserver的更多相关文章
- Python爬虫Urllib库的高级用法
Python爬虫Urllib库的高级用法 设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Head ...
- Python中第三方库Requests库的高级用法详解
Python中第三方库Requests库的高级用法详解 虽然Python的标准库中urllib2模块已经包含了平常我们使用的大多数功能,但是它的API使用起来让人实在感觉不好.它已经不适合现在的时代, ...
- 进击的Python【第五章】:Python的高级应用(二)常用模块
Python的高级应用(二)常用模块学习 本章学习要点: Python模块的定义 time &datetime模块 random模块 os模块 sys模块 shutil模块 ConfigPar ...
- Python底层socket库
Python底层socket库将Unix关于网络通信的系统调用对象化处理,是底层函数的高级封装,socket()函数返回一个套接字,它的方法实现了各种套接字系统调用.read与write与Python ...
- python网络编程socket /socketserver
提起网络编程,不同于web编程,它主要是C/S架构,也就是服务器.客户端结构的.对于初学者而言,最需要理解的不是网络的概念,而是python对于网络编程都提供了些什么模块和功能.不同于计算机发展的初级 ...
- 【python】标准库的大致认识
正如那句 Python 社区中很有名的话所说的:“battery included”,Python 的一大好处在于它有一套很有用的标准库(standard library).标准库是随着 Python ...
- python的urllib2库详细使用说明
一直以来技术群里会有新入行的同学提问关于urllib和urllib2以及cookielib相关的问题.所以我打算在这里总结一下,避免大家反复回答同样的问题浪费资源. 这篇属于教程类的文字,如果你已经非 ...
- python 各种开源库
测试开发 来源:https://www.jianshu.com/p/ea6f7fb69501 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. 链接 sel ...
- python 三方面库整理
测试开发 Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. selenium - web UI自动化测试. –推荐 mechanize- Python中有状 ...
随机推荐
- 【数学建模】MATLAB学习笔记——函数式文件
MATLAB学习笔记——函数式文件 引入函数式文件 说明: 函数式文件主要用于解决计算中的参数传递和函数调用的问题. 函数式的标志是它的第一行为function语句. 函数式文件可以有返回值,也可以没 ...
- Loadrunder脚本篇——文件下载
下载简介 对 HTTP协议来说,无论是下载文件或者请求页面,对客户端来说,都只是发出一个GET请求,并不会记录点击后的“保存”.“另存为操作”. 如下,点击页面中tar.gz压缩包,用工具可以清楚的看 ...
- C# partial 关键字
C# partial关键字详解 partial关键字允许把类.结构或接口放在多个文件中.一般情况下,一个类存储在单个文件中.但有时,多个开发人员需要访问同一个类,或者某种类型的代码生成器生成了一个类的 ...
- Swift中字典解析后的问题,!?两种拆包的差别
给出一个json,使用SwiftyJSON解析传给model,传进去是个字典,字典里有String,NSNumber,NSDoctionary,和NSArray. 正常情况下直接使用下面的解析方法即可 ...
- UI控件之UIScrollView
UIScrollView:提供了滚动功能,用来显示超过一屏的视图 创建滚动视图 UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame: ...
- Android DDMS应用
具体可见http://developer.android.com/tools/debugging/ddms.html. DDMS为IDE和emultor.真正的android设备架起来了一座桥梁.开发 ...
- ACM训练小结-2018年6月19日
今天题目情况如下: A题:考察图论建模+判割点.B题:考察基础数据结构的运用(STL).C题:考察数学建模+运算.(三分可解)D题:考察读题+建模+数据结构的运用.E题:考察图论+贪心.F题:考察图 ...
- C++逗号表达式
c++中,逗号表达式的结果是最右边表达式的值
- linux 安装mysql服务
1.检查是否已安装,grep的-i选项表示匹配时忽略大小写 rpm -qa|grep -i mysql *可见已经安装了库文件,应该先卸载,不然会出现覆盖错误.注意卸:载时使用了--nodeps选项, ...
- LeetCode——sum-root-to-leaf-numbers
Question Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a ...