百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python Web静态服务器-非堵塞模式

off999 2024-09-20 22:50 21 浏览 0 评论

单进程非堵塞 模型

#coding=utf-8
from socket import *
import time
# 用来存储所有的新链接的socket
g_socket_list = list()
def main():
 server_socket = socket(AF_INET, SOCK_STREAM)
 server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR , 1)
 server_socket.bind(('', 7890))
 server_socket.listen(128)
 # 将套接字设置为非堵塞
 # 设置为非堵塞后,如果accept时,恰巧没有客户端connect,那么accept会
 # 产生一个异常,所以需要try来进行处理
 server_socket.setblocking(False)
 while True:
 # 用来测试
 time.sleep(0.5)
 try:
 newClientInfo = server_socket.accept()
 except Exception as result:
 pass
 else:
 print("一个新的客户端到来:%s" % str(newClientInfo))
 newClientInfo[0].setblocking(False) # 设置为非堵塞
 g_socket_list.append(newClientInfo)
 for client_socket, client_addr in g_socket_list:
 try:
 recvData = client_socket.recv(1024)
 if recvData:
 print('recv[%s]:%s' % (str(client_addr), recvData))
 else:
 print('[%s]客户端已经关闭' % str(client_addr))
 client_socket.close()
 g_socket_list.remove((client_socket,client_addr))
 except Exception as result:
 pass
 print(g_socket_list) # for test
if __name__ == '__main__':
 main()

web静态服务器-单进程非堵塞

import time
import socket
import sys
import re
class WSGIServer(object):
 """定义一个WSGI服务器的类"""
 def __init__(self, port, documents_root):
 # 1. 创建套接字
 self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 # 2. 绑定本地信息
 self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 self.server_socket.bind(("", port))
 # 3. 变为监听套接字
 self.server_socket.listen(128)
 self.server_socket.setblocking(False)
 self.client_socket_list = list()
 self.documents_root = documents_root
 def run_forever(self):
 """运行服务器"""
 # 等待对方链接
 while True:
 # time.sleep(0.5) # for test
 try:
 new_socket, new_addr = self.server_socket.accept()
 except Exception as ret:
 print("-----1----", ret) # for test
 else:
 new_socket.setblocking(False)
 self.client_socket_list.append(new_socket)
 for client_socket in self.client_socket_list:
 try:
 request = client_socket.recv(1024).decode('utf-8')
 except Exception as ret:
 print("------2----", ret) # for test
 else:
 if request:
 self.deal_with_request(request, client_socket)
 else:
 client_socket.close()
 self.client_socket_list.remove(client_socket)
 print(self.client_socket_list)
 def deal_with_request(self, request, client_socket):
 """为这个浏览器服务器"""
 if not request:
 return
 request_lines = request.splitlines()
 for i, line in enumerate(request_lines):
 print(i, line)
 # 提取请求的文件(index.html)
 # GET /a/b/c/d/e/index.html HTTP/1.1
 ret = re.match(r"([^/]*)([^ ]+)", request_lines[0])
 if ret:
 print("正则提取数据:", ret.group(1))
 print("正则提取数据:", ret.group(2))
 file_name = ret.group(2)
 if file_name == "/":
 file_name = "/index.html"
 # 读取文件数据
 try:
 f = open(self.documents_root+file_name, "rb")
 except:
 response_body = "file not found, 请输入正确的url"
 response_header = "HTTP/1.1 404 not found\r\n"
 response_header += "Content-Type: text/html; charset=utf-8\r\n"
 response_header += "Content-Length: %d\r\n" % (len(response_body))
 response_header += "\r\n"
 # 将header返回给浏览器
 client_socket.send(response_header.encode('utf-8'))
 # 将body返回给浏览器
 client_socket.send(response_body.encode("utf-8"))
 else:
 content = f.read()
 f.close()
 response_body = content
 response_header = "HTTP/1.1 200 OK\r\n"
 response_header += "Content-Length: %d\r\n" % (len(response_body))
 response_header += "\r\n"
 # 将header返回给浏览器
 client_socket.send( response_header.encode('utf-8') + response_body)
# 设置服务器服务静态资源时的路径
DOCUMENTS_ROOT = "./html"
def main():
 """控制web服务器整体"""
 # python3 xxxx.py 7890
 if len(sys.argv) == 2:
 port = sys.argv[1]
 if port.isdigit():
 port = int(port)
 else:
 print("运行方式如: python3 xxx.py 7890")
 return
 print("http服务器使用的port:%s" % port)
 http_server = WSGIServer(port, DOCUMENTS_ROOT)
 http_server.run_forever()
if __name__ == "__main__":
 main()

相关推荐

python入门到脱坑经典案例—清空列表

在Python中,清空列表是一个基础但重要的操作。clear()方法是最直接的方式,但还有其他方法也可以实现相同效果。以下是详细说明:1.使用clear()方法(Python3.3+推荐)...

python中元组,列表,字典,集合删除项目方式的归纳

九三,君子终日乾乾,夕惕若,厉无咎。在使用python过程中会经常遇到这四种集合数据类型,今天就对这四种集合数据类型中删除项目的操作做个总结性的归纳。列表(List)是一种有序和可更改的集合。允许重复...

Linux 下海量文件删除方法效率对比,最慢的竟然是 rm

Linux下海量文件删除方法效率对比,本次参赛选手一共6位,分别是:rm、find、findwithdelete、rsync、Python、Perl.首先建立50万个文件$testfor...

数据结构与算法——链式存储(链表)的插入及删除,

持续分享嵌入式技术,操作系统,算法,c语言/python等,欢迎小友关注支持上篇文章我们讲述了链表的基本概念及一些查找遍历的方法,本篇我们主要将一下链表的插入删除操作,以及采用堆栈方式如何创建链表。链...

Python自动化:openpyxl写入数据,插入删除行列等基础操作

importopenpyxlwb=openpyxl.load_workbook("example1.xlsx")sh=wb['Sheet1']写入数据#...

在Linux下软件的安装与卸载(linux里的程序的安装与卸载命令)

通过apt安装/协助软件apt是AdvancedPackagingTool,是Linux下的一款安装包管理工具可以在终端中方便的安装/卸载/更新软件包命令使用格式:安装软件:sudoapt...

Python 批量卸载关联包 pip-autoremove

pip工具在安装扩展包的时候会自动安装依赖的关联包,但是卸载时只删除单个包,无法卸载关联的包。pip-autoremove就是为了解决卸载关联包的问题。安装方法通过下面的命令安装:pipinsta...

用Python在Word文档中插入和删除文本框

在当今自动化办公需求日益增长的背景下,通过编程手段动态管理Word文档中的文本框元素已成为提升工作效率的关键技术路径。文本框作为文档排版中灵活的内容容器,既能承载多模态信息(如文字、图像),又可实现独...

Python 从列表中删除值的多种实用方法详解

#Python从列表中删除值的多种实用方法详解在Python编程中,列表(List)是一种常用的数据结构,具有动态可变的特性。当我们需要从列表中删除元素时,根据不同的场景(如按值删除、按索引删除、...

Python 中的前缀删除操作全指南(python删除前导0)

1.字符串前缀删除1.1使用内置方法Python提供了几种内置方法来处理字符串前缀的删除:#1.使用removeprefix()方法(Python3.9+)text="...

每天学点Python知识:如何删除空白

在Python中,删除空白可以分为几种不同的情况,常见的是针对字符串或列表中空白字符的处理。一、删除字符串中的空白1.删除字符串两端的空白(空格、\t、\n等)使用.strip()方法:s...

Linux系统自带Python2&yum的卸载及重装

写在前面事情的起因是我昨天在测试Linux安装Python3的shell脚本时,需要卸载Python3重新安装一遍。但是通过如下命令卸载python3时,少写了个3,不小心将系统自带的python2也...

如何使用Python将多个excel文件数据快速汇总?

在数据分析和处理的过程中,Excel文件是我们经常会遇到的数据格式之一。本文将通过一个具体的示例,展示如何使用Python和Pandas库来读取、合并和处理多个Excel文件的数据,并最终生成一个包含...

【第三弹】用Python实现Excel的vlookup功能

今天继续用pandas实现Excel的vlookup功能,假设我们的2个表长成这样:我们希望把Sheet2的部门匹在Sheet1的最后一列。话不多说,先上代码:importpandasaspd...

python中pandas读取excel单列及连续多列数据

案例:想获取test.xls中C列、H列以后(当H列后列数未知时)的所有数据。importpandasaspdfile_name=r'D:\test.xls'#表格绝对...

取消回复欢迎 发表评论: