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

1. Python之socketserver架构

  

2. 如何创建一个socketserver 

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

示例:SocketServer.py

  1. #coding:UTF-8
  2.  
  3. ''' socketserver模块实例 '''
  4.  
  5. import socket
  6. import socketserver
  7.  
  8. hostname = socket.gethostname()
  9. ip = socket.gethostbyname(hostname)
  10. ip_port = (ip, 1122)
  11.  
  12. class Myhandler(socketserver.BaseRequestHandler):
  13. def handle(self):
  14. print (ip_port)
  15. print (self.request, self.client_address, self.server)
  16. while True:
  17. data = self.request.recv(1024)
  18. print (len(data))
  19. if len(data) > 0:
  20. print (data, self.client_address)
  21. data1 = data.decode("utf8").lower()
  22. print (data1)
  23. if data1 == "exit":
  24. print ("server exit")
  25. break
  26.  
  27. if __name__ == "__main__":
  28. s =socketserver.ThreadingTCPServer((ip_port),Myhandler)
  29. print (s)
  30. 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重用地址

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.

 
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.

Python---socketserver的更多相关文章

  1. 使用Python SocketServer快速实现多线程网络服务器

    Python SocketServer使用介绍 1.简介: SocketServer是python的一个网络服务器框架,可以减少开发人员编写网络服务器程序的工作量. SocketServer总共有4个 ...

  2. python socketserver实现客户端多并发

    直接看代码 server #!/usr/bin/env python # -*- coding:utf-8 -*- import socketserver import subprocess clas ...

  3. python socketserver框架解析

    socketserver框架是一个基本的socket服务器端框架, 使用了threading来处理多个客户端的连接, 使用seletor模块来处理高并发访问, 是值得一看的python 标准库的源码之 ...

  4. Python SocketServer源码分析

    1      XXXServer 1.1      BaseSever 提供基础的循环等待请求的处理框架.使用serve_forever启动服务,使用shutdown停止.同时提供了一些可自行扩展的方 ...

  5. python SocketServer 源码分析

    附上原文链接: http://beginman.cn/python/2015/04/06/python-SocketServer/

  6. python socketserver监听多端口多进程

    多进程监听多端口 # 多线程socket # 程序监听两个端口,端口逻辑相同其中一个端口放在子进程下 # 每次请求会在产生一个进程处理请求 import SocketServer from multi ...

  7. Python——socketserver编程(客户端/服务器)

    一.socketserver是标准库中的高级模块,它的目标是简化很多多样板代码,是创建网络客户端和服务器所必须的代码.(事件驱动) 二.模块类 BaseServer :包含核心服务器功能和mix-in ...

  8. python - socketserver 模块应用

    server端: import socketserver import subprocess import json import struct class MyTCPHandler(socketse ...

  9. Python socketserver模块解析

    参考:https://blog.csdn.net/qq_33733970/article/details/79153938 1.功能简介 socketserver模块是对socket模块的再封装,用于 ...

  10. Python socketserver ftp功能简单讲解

    socketserver模块实现并发 为什么要讲socketserver?我们之前写的tcp协议的socket是不是一次只能和一个客户端通信,如果用socketserver可以实现和多个客户端通信.它 ...

随机推荐

  1. AdaBoost入门

    写一点自己理解的AdaBoost,然后再贴上面试过程中被问到的相关问题.按照以下目录展开. 当然,也可以去我的博客上看 Boosting提升算法 AdaBoost 原理理解 实例 算法流程 公式推导 ...

  2. vb代码之-------当窗体BorderStyle属性为0时,添加窗口预览到任务栏

    入吾QQ群183435019 (学习 交流+唠嗑) 有很多时候,我们为了美观,将会自己画一个标题栏,这时候我们会把原来的标题栏取消掉,最简单的方法是吧窗体的BorderStyle设置成为0, 然后自己 ...

  3. 12、ABPZero系列教程之拼多多卖家工具 拼团提醒功能登录拼多多实现

    上篇文章已经完成了整个拼多多拼团提醒功能,本篇继续完成拼多多帐号登录,拼多多帐号登录的目的是为了获取拼团商品的SKU和订单号,便于商家备货. 以下是拼多多官方的后台登录,要实现的功能并不是直接在这里登 ...

  4. NPOI操作Excel 踩坑记

    1 读取Excel并修改单元格 a.一定不能一边读数据,一边修改单元格,否则读出来的数据可能不准 b.注意写文件的模式,不然修改后的文件,打开会报错. c.清空单元格的数据,可以调用SetCellTy ...

  5. vue.js之路由

    Vue.js本身只提供数据与视图绑定及组件化等功能,如果想用它来开发一个完整的SPA(单页面应用),我们就还需要使用一些Vue.js的插件.今天我学习一种叫做Vue-router的插件,用来提供路由管 ...

  6. Sql的基础知识提升(二)

    二.提升 1.说明:复制表(只复制结构,源表名:a 新表名:b) (Access 可用) 法一:select * into b from a where 1<>1(仅用于 SQlServe ...

  7. POJ 3673 Cow Multiplication

    Cow Multiplication Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 13312   Accepted: 93 ...

  8. BZOJ 3038: 上帝造题的七分钟2【线段树区间开方问题】

    3038: 上帝造题的七分钟2 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 1469  Solved: 631[Submit][Status][Dis ...

  9. [51nod1206]Picture

    给你一坨矩形,问这些矩形组成的所有多边形的周长之和. 分别求竖着的边和横着的边. 离散化后线段树,维护当前行(或者列)有多少没在多边形里的,添加矩形就变成添加.删除线段. 每次加线段或删线段时累加一下 ...

  10. Codeforces 626C

                                                                                                        ...