zoukankan      html  css  js  c++  java
  • python-协程、线程、进程多任务实现http 服务器

    import socket
    from multiprocessing import Process
    import threading
    from gevent import monkey
    import gevent
    import re

    monkey.patch_all()


    def handle_client(client_socket):
    """
    处理客户端请求
    """
    request_data = client_socket.recv(1024).decode('utf-8')

    request_lines = request_data.splitlines()
    ret = re.match(r'[^/]+(/[^ ]*)', request_lines[0])
    print(">>", ret.group(1))
    # 构造响应数据
    response_start_line = "HTTP/1.1 200 OK "
    response_headers = "Server: My server "
    # response_body = "<h1>Python HTTP Test</h1>"

    f = open('index.html', 'rb')
    response_body = f.read()
    f.close()
    response = response_start_line + response_headers + " " #+ response_body

    # 向客户端返回响应数据
    client_socket.send(bytes(response, "utf-8"))
    client_socket.send(response_body)
    # 关闭客户端连接
    client_socket.close()


    if __name__ == "__main__":
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(("", 1122))
    server_socket.listen(128)

    while True:
    client_socket, client_address = server_socket.accept()
    print("[%s, %s]用户连接上了" % client_address)
    '''
    # 下面三行为多进程(进程需要close,因为子进程复制了进程的代码)
    # handle_client_process = Process(target=handle_client, args=(client_socket,))
    # handle_client_process.start()
    # client_socket.close()
    '''
    '''
    # 下面两行为多线程
    t1 = threading.Thread(target=handle_client, args=(client_socket,))
    t1.start()
    '''
    # 下面为协程
    g1 = gevent.spawn(handle_client, client_socket)


  • 相关阅读:
    MongoDB ObjectId
    MongoDB固定集合
    MongoDB 正则表达式
    MongoDB Map Reduce
    MongoDB操作
    VIM跳到指定行
    linux之echo命令
    rpm and yum commands
    CentOS 7 下的软件安装建议
    apt系统中sources.list文件的解析
  • 原文地址:https://www.cnblogs.com/fuyouqiang/p/11776879.html
Copyright © 2011-2022 走看看