zoukankan      html  css  js  c++  java
  • Web服务器-并发服务器-协程 (3.4.2)

    @

    1.分析

    随着网站的用户量越来愈多,通过多进程多线程的会力不从心
    使用协程可以缓解这一问题
    只要使用gevent实现

    2.代码

    from socket import *
    import  re
    from gevent import monkey
    import gevent
    
    monkey.patch_all()
    def service_client(new_socket):
        '''为这个客户端返回数据'''
    
        # 1.接收浏览器发送过来的请求,即http请求
        #GET /HTTP/1.1
        # ...
        request = new_socket.recv(1024).decode("utf-8")
        request_lines = request.splitlines()
        print(request_lines)
    
        #GET /index.html HTTP/1.1
        #get post put del
        ret = re.match(r"[^/]+/[^ ]*",request_lines[0])
        file_name = ""
        if ret:
            file_name = ret.group(0)
    
        #2,返回http格式的数据给浏览器
        #2.1准备发送给浏览器的数据 ---header
        response = "HTTP/1.1 200 OK
    "#正常浏览器
    代表的是换行
        response += "
    "
        #2.2准备发送给浏览器的数据
        response =  response + file_name
        new_socket.send(response.encode("utf-8"))
    
        #3.关闭套接字
        new_socket.close()
    
    
    def main():
        '''用来完成整体的控制'''
        #1.创建套接字
        tcp_server_socket = socket(AF_INET, SOCK_STREAM)
    
        # 2.绑定本地信息
        port = 7777
        address = ('', port)
        tcp_server_socket.bind(address)
    
        # 3.变为监听,将主动套接字变为被动套接字
        tcp_server_socket.listen(128)
    
        #等待连接
        while True:
            client_socket, clientAddr = tcp_server_socket.accept()
    
            #协程
            gevent.spawn(service_client,client_socket)
    
    
            #线程和进程都是共享的
            # client_socket.close()
    
        # 关闭监听套接字
        tcp_server_socket.close()
    
    
    if __name__ == "__main__":
        main()
    
    

    关于作者

    个人博客网站
    个人GitHub地址
    个人公众号:
    在这里插入图片描述

  • 相关阅读:
    python 学习 3-1 (编码)
    mongdb备份
    docker 部署redis , mongodb ,rabbitmq
    python学习第一天第二天总结
    python 学习 (1-3)
    python学习(day1-2)
    Activiti工作流搭建教程
    docker Compose安装
    CAS 单点登录(代码部分)
    推送自定义docker镜像到阿里云
  • 原文地址:https://www.cnblogs.com/simon-idea/p/11399471.html
Copyright © 2011-2022 走看看