多进程实现http服务器
导入multiprocessing模块
import multiprocessing
打开一个进程给客户端,在主进程先关闭new_socket.close()
while True:
# 客户端连接
new_socket,client_addr = tcp_server_socket.accept()
# 打开一个线程给客户端
p = multiprocessing.Process(target=client_socket,args=(new_socket,))
p.start()
new_socket.close()
代码:(其他部分与上一章一样)
import socket
import multiprocessing
import re
def client_socket(new_socket):
recv_data = new_socket.recv(1024).decode("utf-8")
print (recv_data)
request_lines = recv_data.splitlines()
print(">"*20)
print (request_lines)
# 用正则表达式把recv_data的值提取出来
ret = re.match(r"[^/]+(/[^ ]*)",request_lines[0])
if ret:
html_name = ret.group(1)
print (html_name)
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
try:
f = open("." + html_name,"rb")
except:
response = "HTTP/1.1 404 NOT found\r\n"
response += "\r\n"
response += "-----file not found----"
new_socket.send(response.encode("utf-8"))
else:
html_content = f.read()
f.close()
new_socket.send(response.encode("utf-8"))
new_socket.send(html_content)
new_socket.close()
def main():
# 打开套接字
tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定端口
localaddr = ("",8080)
tcp_server_socket.bind(localaddr)
# 转为接听模式
tcp_server_socket.listen(128)
while True:
# 客户端连接
new_socket,client_addr = tcp_server_socket.accept()
# 打开一个线程给客户端
p = multiprocessing.Process(target=client_socket,args=(new_socket,))
p.start()
new_socket.close()
# 关闭套接字
tcp_server_socket.close()
if __name__ == '__main__':
main()
多线程实现http服务器
导入threading模块
import threading
打开一个线程给客户端,在主线程不用关闭new_socket.close()
while True:
# 客户端连接
new_socket,client_addr = tcp_server_socket.accept()
# 打开一个线程给客户端
p = threading.Thread(target=client_socket,args=(new_socket,))
p.start()
# 关闭套接字
tcp_server_socket.close()
代码:(其他部分与上一章一样)
import socket
import threading
import re
def client_socket(new_socket):
recv_data = new_socket.recv(1024).decode("utf-8")
print (recv_data)
request_lines = recv_data.splitlines()
print(">"*20)
print (request_lines)
# 用正则表达式把recv_data的值提取出来
ret = re.match(r"[^/]+(/[^ ]*)",request_lines[0])
if ret:
html_name = ret.group(1)
print (html_name)
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
try:
f = open("." + html_name,"rb")
except:
response = "HTTP/1.1 404 NOT found\r\n"
response += "\r\n"
response += "-----file not found----"
new_socket.send(response.encode("utf-8"))
else:
html_content = f.read()
f.close()
new_socket.send(response.encode("utf-8"))
new_socket.send(html_content)
new_socket.close()
def main():
# 打开套接字
tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定端口
localaddr = ("",8080)
tcp_server_socket.bind(localaddr)
# 转为接听模式
tcp_server_socket.listen(128)
while True:
# 客户端连接
new_socket,client_addr = tcp_server_socket.accept()
# 打开一个线程给客户端
p = threading.Thread(target=client_socket,args=(new_socket,))
p.start()
# 关闭套接字
tcp_server_socket.close()
if __name__ == '__main__':
main()
- 问题,为什么要在主进程也close(),在子进程也close()
而在主线程不close()
进程之间的变量互相独立,线程共享全局变量。
就是主线程关闭了,子线程当中其实也相当于关闭了,共享全局变量。
而进程之间复制一份,是各自的资源,主进程关闭了,子进程并不会关闭。