1.线程、进程实现多任务HTTP服务器
import re
import socket
import multiprocessing
import threading
def service_client(new_socket):
"""为这个客户端返回数据"""
# 接收浏览器发送过来的请求,即HTTP请求
request=new_socket.recv(1024)
request=request.decode("utf-8") # 解码
request_lines=request.splitlines() # 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表
print(request_lines)
# GET /index.html HTTP/1.1
# [^/]表示除了/都可以
file_name=""
ret=re.match(r"[^/]+(/[^ ]*)",request_lines[0])
if ret:
file_name=ret.group(1)
if file_name=="/":
file_name="/index.html"
# 2.返回HTTP格式的数据,给浏览器
try:
# 准备发送的body,打开HTML文件
f=open("html"+file_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()
# 准备发送的header
response="HTTP/1.1 200 OK\r\n"
response+="\r\n" # header与body之间必须隔一行
# 发送header
new_socket.send(response.encode("utf-8"))
# 发送HTML
new_socket.send(html_content)
new_socket.close()
def main():
tcp_sever_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 服务器先关闭,保证重新开启不占用端口
tcp_sever_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
tcp_sever_socket.bind(("",7890))
tcp_sever_socket.listen(128)
while True:
# 等待新客户端的链接
new_socket,client_addr=tcp_sever_socket.accept()
#p=multiprocessing.Process(target=service_client,args=(new_socket,))
p=threading.Thread(target=service_client,args=(new_socket,))
p.start()
# 子进程关闭一次主进程还需关闭一次,Linux下文件硬链接的原因,两个名字指向同一个文件,因此要关闭两次
#new_socket.close()
# 关闭监听套接字
tcp_sever_socket.close()
if __name__ == '__main__':
main()
2.gevent协程实现多任务HTTP服务器
import re
import socket
import gevent
from gevent import monkey
monkey.patch_all()
def service_client(new_socket):
"""为这个客户端返回数据"""
# 接收浏览器发送过来的请求,即HTTP请求
request=new_socket.recv(1024)
request=request.decode("utf-8") # 解码
request_lines=request.splitlines() # 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表
print(request_lines)
# GET /index.html HTTP/1.1
# [^/]表示除了/都可以
file_name=""
ret=re.match(r"[^/]+(/[^ ]*)",request_lines[0])
if ret:
file_name=ret.group(1)
if file_name=="/":
file_name="/index.html"
# 2.返回HTTP格式的数据,给浏览器
try:
# 准备发送的body,打开HTML文件
f=open("html"+file_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()
# 准备发送的header
response="HTTP/1.1 200 OK\r\n"
response+="\r\n" # header与body之间必须隔一行
# 发送header
new_socket.send(response.encode("utf-8"))
# 发送HTML
new_socket.send(html_content)
new_socket.close()
def main():
tcp_sever_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 服务器先关闭,保证重新开启不占用端口
tcp_sever_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
tcp_sever_socket.bind(("",7890))
tcp_sever_socket.listen(128)
while True:
# 等待新客户端的链接
new_socket,client_addr=tcp_sever_socket.accept()
gevent.spawn(service_client,new_socket)
# 关闭监听套接字
tcp_sever_socket.close()
if __name__ == '__main__':
main()