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 SocketServer快速实现多线程网络服务器
Python SocketServer使用介绍 1.简介: SocketServer是python的一个网络服务器框架,可以减少开发人员编写网络服务器程序的工作量. SocketServer总共有4个 ...
- python socketserver实现客户端多并发
直接看代码 server #!/usr/bin/env python # -*- coding:utf-8 -*- import socketserver import subprocess clas ...
- python socketserver框架解析
socketserver框架是一个基本的socket服务器端框架, 使用了threading来处理多个客户端的连接, 使用seletor模块来处理高并发访问, 是值得一看的python 标准库的源码之 ...
- Python SocketServer源码分析
1 XXXServer 1.1 BaseSever 提供基础的循环等待请求的处理框架.使用serve_forever启动服务,使用shutdown停止.同时提供了一些可自行扩展的方 ...
- python SocketServer 源码分析
附上原文链接: http://beginman.cn/python/2015/04/06/python-SocketServer/
- python socketserver监听多端口多进程
多进程监听多端口 # 多线程socket # 程序监听两个端口,端口逻辑相同其中一个端口放在子进程下 # 每次请求会在产生一个进程处理请求 import SocketServer from multi ...
- Python——socketserver编程(客户端/服务器)
一.socketserver是标准库中的高级模块,它的目标是简化很多多样板代码,是创建网络客户端和服务器所必须的代码.(事件驱动) 二.模块类 BaseServer :包含核心服务器功能和mix-in ...
- python - socketserver 模块应用
server端: import socketserver import subprocess import json import struct class MyTCPHandler(socketse ...
- Python socketserver模块解析
参考:https://blog.csdn.net/qq_33733970/article/details/79153938 1.功能简介 socketserver模块是对socket模块的再封装,用于 ...
- Python socketserver ftp功能简单讲解
socketserver模块实现并发 为什么要讲socketserver?我们之前写的tcp协议的socket是不是一次只能和一个客户端通信,如果用socketserver可以实现和多个客户端通信.它 ...
随机推荐
- Cenots更换YUM源的问题
[1] 首先备份/etc/yum.repos.d/CentOS-Base.repo mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/Cent ...
- 一键下载你的youtube视频
很多人喜欢逛油管看视频,自然就会有一些喜欢的收藏集或者视频作者,有时候想要下载下来保存在本地播放,这样的话就不用每次FQ,毕竟有些代理的速度并不是很理想(如果你的代理速度炒鸡快的话,请忽略这篇文章). ...
- Python3——让我们像孩子一样的去看书
用tkinter来画高级图形 让我们一起创造一个按钮吧!"按住我:0 :" 那我们先做一个小例子,让我们第一眼先认识到这个它(tkinter)吧! 输入以下代码: from tk ...
- CTF---安全杂项入门第三题 这是捕获的黑客攻击数据包,Administrator用户的密码在此次攻击中泄露了,你能找到吗?
这是捕获的黑客攻击数据包,Administrator用户的密码在此次攻击中泄露了,你能找到吗?分值:30 来源: 2014sctf 难度:难 参与人数:3918人 Get Flag:384人 答题人数 ...
- bzoj 3065: 带插入区间K小值(分块)
Description 从前有n只跳蚤排成一行做早操,每只跳蚤都有自己的一个弹跳力a[i].跳蚤国王看着这些跳蚤国欣欣向荣的情景,感到非常高兴.这时跳蚤国王决定理性愉悦一下,查询区间k小值.他每次向它 ...
- Codeforces Round #410 (Div. 2)(A,字符串,水坑,B,暴力枚举,C,思维题,D,区间贪心)
A. Mike and palindrome time limit per test:2 seconds memory limit per test:256 megabytes input:stand ...
- 51 Nod 1057 N的阶乘【Java大数乱搞】
1057 N的阶乘 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 输入N求N的阶乘的准确值. Input 输入N(1 <= N <= 10000) Ou ...
- callback和spring的MD5加密
举个例子:当我们访问淘宝网站的时候,当点击购物车的时候,这个时候提示用户登录用户名和密码,登录成功后,会返回到购物车的页面.这就是回调. 它不返回淘宝的首页,而是返回到我们点击的内容所在页面. 在写接 ...
- Android中与task相关的几个属性
1.与任务相关的属性 taskAffinity :修改任何给定Activity的关联 系统使用包名标识应用的默认任务关联: taskAffinity属性取字符串值,必须不同于包名: taskAffin ...
- [国嵌攻略][054][NandFlash驱动设计_写]
Nand Flash支持按页写和随机写两种方式,在下面实现的是按页写.闪存在写数据时,只能写入1,不能写入0,所以写函数必须和擦除函数一起使用,并且擦除函数是按块擦除. /************** ...