我一直在遵循一个教程来编写Python Weberver: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个客户可以在不等待上一个子过程结束的情况下获取网页?
?(当然我可以删除睡眠((函数,但这并不能真正解决问题(
使用新线程接受客户端的连接