如何在Web服务器(python)中实现多处理?

时间:2017-05-03 20:00:27

标签: python server webserver multiprocessing python-multiprocessing

我一直在学习编写python webserver的教程: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()函数,但这不会真正解决问题)

1 个答案:

答案 0 :(得分:0)

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