18 11 26 用多进程 多线程 携程 实现 http 服务器的创建

Posted Mr喃先森

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了18 11 26 用多进程 多线程 携程 实现 http 服务器的创建相关的知识,希望对你有一定的参考价值。

下面是一个  多进程 服务器的创建  

import socket
import re
import multiprocessing

def service_client(new_socket):
    """为这个客户端返回数据"""

    # 1. 接收浏览器发送过来的请求 ,即http请求
    # GET / HTTP/1.1
    # .....
    request = new_socket.recv(1024).decode("utf-8")  # 浏览器当收到一个请求之后  由于有图片等(有超链接的) 又会提出新的请求
    # print(">>>"*50)
    # print(request)

    request_lines = request.splitlines()  # Python splitlines() 按照行(‘
‘, ‘
‘, 
‘)分隔,返回一个包含各行作为元素的列表
    print("")
    print(">" * 20)
    print(request_lines)

    # GET /index.html HTTP/1.1
    # get post put del
    file_name = ""
    ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
    if ret:
        file_name = ret.group(1)
        # print("*"*50, file_name)
        if file_name == "/":
            file_name = "/index.html"

    # 2. 返回http格式的数据,给浏览器

    try:
        f = open("./html" + file_name, "rb")
    except:
        response = "HTTP/1.1 404 NOT FOUND
"
        response += "
"
        response += "------file not found-----"
        new_socket.send(response.encode("utf-8"))
    else:
        html_content = f.read()
        f.close()
        # 2.1 准备发送给浏览器的数据---header
        response = "HTTP/1.1 200 OK
"
        response += "
"
        # 2.2 准备发送给浏览器的数据---boy
        # response += "hahahhah"

        # 将response header发送给浏览器
        new_socket.send(response.encode("utf-8"))
        # 将response body发送给浏览器
        new_socket.send(html_content)

    # 关闭套接
    new_socket.close()


def main():
    """用来完成整体的控制"""
    # 1. 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 2. 绑定
    tcp_server_socket.bind(("", 7890))

    # 3. 变为监听套接字
    tcp_server_socket.listen(128)

    while True:
        # 4. 等待新客户端的链接
        new_socket, client_addr = tcp_server_socket.accept()

        # 5. 为这个客户端服务
        # service_client(new_socket)  # 下面用了多进程的方法代替了这句话
        p = multiprocessing.Process(target = service_client, args = (new_socket,))
        p.start()
        new_socket.close()


    # 关闭监听套接字
    tcp_server_socket.close()


if __name__ == "__main__":
    main()

下面是一个多进程的  http  服务器

import socket
import re
import threading

def service_client(new_socket):
    """为这个客户端返回数据"""

    # 1. 接收浏览器发送过来的请求 ,即http请求
    # GET / HTTP/1.1
    # .....
    request = new_socket.recv(1024).decode("utf-8")  # 浏览器当收到一个请求之后  由于有图片等(有超链接的) 又会提出新的请求
    # print(">>>"*50)
    # print(request)

    request_lines = request.splitlines()  # Python splitlines() 按照行(‘
‘, ‘
‘, 
‘)分隔,返回一个包含各行作为元素的列表
    print("")
    print(">" * 20)
    print(request_lines)

    # GET /index.html HTTP/1.1
    # get post put del
    file_name = ""
    ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
    if ret:
        file_name = ret.group(1)
        # print("*"*50, file_name)
        if file_name == "/":
            file_name = "/index.html"

    # 2. 返回http格式的数据,给浏览器

    try:
        f = open("./html" + file_name, "rb")
    except:
        response = "HTTP/1.1 404 NOT FOUND
"
        response += "
"
        response += "------file not found-----"
        new_socket.send(response.encode("utf-8"))
    else:
        html_content = f.read()
        f.close()
        # 2.1 准备发送给浏览器的数据---header
        response = "HTTP/1.1 200 OK
"
        response += "
"
        # 2.2 准备发送给浏览器的数据---boy
        # response += "hahahhah"

        # 将response header发送给浏览器
        new_socket.send(response.encode("utf-8"))
        # 将response body发送给浏览器
        new_socket.send(html_content)

    # 关闭套接
    new_socket.close()


def main():
    """用来完成整体的控制"""
    # 1. 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 2. 绑定
    tcp_server_socket.bind(("", 7890))

    # 3. 变为监听套接字
    tcp_server_socket.listen(128)

    while True:
        # 4. 等待新客户端的链接
        new_socket, client_addr = tcp_server_socket.accept()

        # 5. 为这个客户端服务
        # service_client(new_socket)  # 下面用了多进程的方法代替了这句话
        p = threading.Thread(target = service_client, args = (new_socket,))
        p.start()
    


    # 关闭监听套接字
    tcp_server_socket.close()


if __name__ == "__main__":
    main()

 

import socket
import re
import gevent
from gevent import monkey

monkey.patch_all()

def service_client(new_socket):
    """为这个客户端返回数据"""

    # 1. 接收浏览器发送过来的请求 ,即http请求
    # GET / HTTP/1.1
    # .....
    request = new_socket.recv(1024).decode("utf-8")  # 浏览器当收到一个请求之后  由于有图片等(有超链接的) 又会提出新的请求
    # print(">>>"*50)
    # print(request)

    request_lines = request.splitlines()  # Python splitlines() 按照行(‘
‘, ‘
‘, 
‘)分隔,返回一个包含各行作为元素的列表
    print("")
    print(">" * 20)
    print(request_lines)

    # GET /index.html HTTP/1.1
    # get post put del
    file_name = ""
    ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
    if ret:
        file_name = ret.group(1)
        # print("*"*50, file_name)
        if file_name == "/":
            file_name = "/index.html"

    # 2. 返回http格式的数据,给浏览器

    try:
        f = open("./html" + file_name, "rb")
    except:
        response = "HTTP/1.1 404 NOT FOUND
"
        response += "
"
        response += "------file not found-----"
        new_socket.send(response.encode("utf-8"))
    else:
        html_content = f.read()
        f.close()
        # 2.1 准备发送给浏览器的数据---header
        response = "HTTP/1.1 200 OK
"
        response += "
"
        # 2.2 准备发送给浏览器的数据---boy
        # response += "hahahhah"

        # 将response header发送给浏览器
        new_socket.send(response.encode("utf-8"))
        # 将response body发送给浏览器
        new_socket.send(html_content)

    # 关闭套接
    new_socket.close()


def main():
    """用来完成整体的控制"""
    # 1. 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 2. 绑定
    tcp_server_socket.bind(("", 7890))

    # 3. 变为监听套接字
    tcp_server_socket.listen(128)

    while True:
        # 4. 等待新客户端的链接
        new_socket, client_addr = tcp_server_socket.accept()

        # 5. 为这个客户端服务
        # service_client(new_socket)  # 下面用了携程的方法代替了这句话
        gevent.spawn(service_client,new_socket)



    # 关闭监听套接字
    tcp_server_socket.close()


if __name__ == "__main__":
    main()

 

以上是关于18 11 26 用多进程 多线程 携程 实现 http 服务器的创建的主要内容,如果未能解决你的问题,请参考以下文章

多进程和多线程

线程进程携程

多进程与多线程差别

进程 vs. 线程

18 11 20 网络通信 ----多任务---- 携程 ----迭代器

Python多进程vs多线程