1

我一直在下面的教程编写一个Web服务器的Python:ruslanspivak.com/lsbaws-part3/如何实现在web服务器(Python)的多处理?

没有为是应该处理请求的利用多重

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秒关闭连接Python的web服务器一个简单的代码。 在15秒,其他客户端仍然应该能够连接并接收该网页,但它似乎像其他客户端必须等待前一个子进程,以便做到这一点结束。

我如何能实现真正的多处理,其中至少4-5客户可以得到网页,而无需等待前一个子进程结束?

(当然我可以删除睡眠()函数,但不会真正解决问题)

回答

0

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

+0

看来,这个问题要避免使用线程,而是使用多处理 – Paul