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

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

off999 2024-09-20 22:50 26 浏览 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文件操作与输入输出

9.1文件的基本操作9.1.1打开文件理论知识:在Python中,使用open()函数来打开文件。open()函数接受两个主要参数:文件名和打开模式。打开模式决定了文件如何被使用,常见的模式有:&...

Python的文件处理

一、文件处理的流程1.打开文件,得到文件句柄并赋值给一个变量2.通过句柄对文件进行操作3.关闭文件示例:d=open('abc')data1=d.read()pri...

Python处理文本的25个经典操作

Python处理文本的优势主要体现在其简洁性、功能强大和灵活性。具体来说,Python提供了丰富的库和工具,使得对文件的读写、处理变得轻而易举。简洁的文件操作接口Python通过内置的open()函数...

Python学不会来打我(84)python复制文件操作总结

上一篇文章我们分享了python读写文件的操作,主要用到了open()、read()、write()等方法。这一次是在文件读写的基础之上,我们分享文件的复制。#python##python自学##...

python 文件操作

1.检查目录/文件使用exists()方法来检查是否存在特定路径。如果存在,返回True;如果不存在,则返回False。此功能在os和pathlib模块中均可用,各自的用法如下。#os模块中e...

《文件操作(读写文件)》

一、文件操作基础1.open()函数核心语法file=open("filename.txt",mode="r",encoding="utf-8"...

栋察宇宙(二十一):Python 文件操作全解析

分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“Python文件操作全解析”欢迎您的访问!Sharethefun,spreadthe...

值得学习练手的70个Python项目(附代码),太实用了

Python丰富的开发生态是它的一大优势,各种第三方库、框架和代码,都是前人造好的“轮子”,能够完成很多操作,让你的开发事半功倍。下面就给大家介绍70个通过Python构建的项目,以此来学习Pytho...

python图形化编程:猜数字的游戏

importrandomnum=random.randint(1,500)running=Truetimes=0##总的次数fromtkinterimport*##导入所有tki...

一文讲清Python Flask的Web编程知识

刚入坑Python做Web开发的新手,还在被配置臃肿、启动繁琐折磨?Flask这轻量级框架最近又火出圈,凭5行代码启动Web服务的极致简洁,让90后程序员小张直呼真香——毕竟他刚用这招把部署时间从半小...

用python 编写一个hello,world

第一种:交互式运行一个hello,world程序:这是写python的第一步,也是学习各类语言的第一步,就是用这种语言写一个hello,world程序.第一步,打开命令行窗口,输入python,第二步...

python编程:如何使用python代码绘制出哪些常见的机器学习图像?

专栏推荐绘图的变量单变量查看单变量最方便的无疑是displot()函数,默认绘制一个直方图,并你核密度估计(KDE)sns.set(color_codes=True)np.random.seed(su...

如何编写快速且更惯用的 Python 代码

Python因其可读性而受到称赞。这使它成为一种很好的第一语言,也是脚本和原型设计的流行选择。在这篇文章中,我们将研究一些可以使您的Python代码更具可读性和惯用性的技术。我不仅仅是pyt...

Python函数式编程的详细分析(代码示例)

本篇文章给大家带来的内容是关于Python函数式编程的详细分析(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。FunctionalProgramming,函数式编程。Py...

编程小白学做题:Python 的经典编程题及详解,附代码和注释(七)

适合Python3+的6道编程练习题(附详解)1.检查字符串是否以指定子串开头题目描述:判断字符串是否以给定子串开头(如"helloworld"以"hello&...

取消回复欢迎 发表评论: