侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python Web静态服务器非堵塞模式实现方法示例

Python  /  管理员 发布于 7年前   191

本文实例讲述了Python Web静态服务器非堵塞模式实现方法。分享给大家供大家参考,具体如下:

单进程非堵塞 模型

#coding=utf-8from socket import *import time# 用来存储所有的新链接的socketg_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 testif __name__ == '__main__':  main()

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

import timeimport socketimport sysimport reclass 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 Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    如何获取Python简单for循环索引
    下一条:
    使用python代码进行身份证号校验的实现示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客