【问题标题】:How to implement multi-processing in a web-server (python)?如何在网络服务器(python)中实现多处理?
【发布时间】:2017-05-03 20:00:27
【问题描述】:

我一直在学习编写 python 网络服务器的教程:ruslanspivak.com/lsbaws-part3/

python web-server 有一个简单的代码,它应该使用多处理来处理请求

import os
import socket
import time

SERVER_ADDRESS = (HOST, PORT) = '', 8888
REQUEST_QUEUE_SIZE = 15

file = open("test.html", "r")
http_response = file.read()

def handle_request(client_connection):
    request = client_connection.recv(1024)

    print(
        'Child PID: {pid}. Parent PID {ppid}'.format(
            pid=os.getpid(),
            ppid=os.getppid(),
        )
    )
    #print(request.decode())
    '''http_response = b"""\
HTTP/1.1 200 OK

Hello, World!
"""'''
    client_connection.sendall(http_response)
    time.sleep(15)


def serve_forever():
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listen_socket.bind(SERVER_ADDRESS)
    listen_socket.listen(REQUEST_QUEUE_SIZE)
    print('Serving HTTP on port {port} ...'.format(port=PORT))
    print('Parent PID (PPID): {pid}\n'.format(pid=os.getpid()))

    while True:
        client_connection, client_address = listen_socket.accept()
        #print "parent is now accepting new clients"
        pid = os.fork()
        if pid == 0:  # child
            #print "aaaaaaaa", pid, "aaaaaaa"
            listen_socket.close()  # close child copy
            handle_request(client_connection)
            client_connection.close()
            print ("child {pid} exits".format(pid=os.getpid()))
            os._exit(0)  # child exits here

        else:  # parent
            print "parent process continues"
            client_connection.close()  # close parent copy and loop over

if __name__ == '__main__':
    serve_forever()

这应该向客户端返回一个简单的网页并等待 15 秒以关闭连接。 在这 15 秒内,其他客户端应该仍然能够连接并接收网页,但似乎其他客户端必须等待前一个子进程结束才能这样做。

如何实现真正的多处理,让至少 4-5 个客户端无需等待前一个子进程结束即可获取网页?

(当然我可以去掉 sleep() 函数,但这并不能真正解决问题)

【问题讨论】:

    标签: python server webserver multiprocessing python-multiprocessing


    【解决方案1】:

    使用新线程接受来自客户端的连接

    【讨论】:

    • 看来问题是想避免使用线程,而是使用多处理
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2015-11-12
    • 2020-03-09
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多