一、多进程完成web服务器实现
import socket
import re
import multiprocessing
def response_request(new_socket):
#接收浏览器请求
request = new_socket.recv(1024).decode("utf-8")
request = request.splitlines()
filename = ''
ret = re.match(r"[^/]+(/[^ ]*)",request[0])
if ret:
filename = ret.group(1)
if filename == '/':
filename = '/a.html'
#print(request)
#给浏览器回送消息
try:
f = open('C:/Users/蓝坚/Desktop/a'+filename,'rb')
except:
response = 'HTTP/1.1 404 NOT FOUND\r\n'
response += '\r\n'
response += '----------'
new_socket.send(response.encode("utf-8"))
else:
html_content = f.read()
f.close()
response = 'HTTP/1.1 200 OK \r\n'
response += '\r\n'
new_socket.send(response.encode("utf-8"))
new_socket.send(html_content)
new_socket.close()
def main():
#创建套接字
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#设置服务器使用固定地址
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#绑定端口
server_socket.bind(('',7890))
#设置套接字处于监听状态
server_socket.listen()
#处理浏览器数据
while True:
new_socket,new_addr = server_socket.accept()
p = multiprocessing.Process(target=request_response,args=(new_socket,))
p.start()
new_socket.close()
#关闭套接字
server_socket.close()
if __name__ == "__main__":
main()
二、多线程完成web服务器实现
import socket
import re
import threading
def request_response(client_socket):
#接收浏览器的请求
request_data = client_socket.recv(1024).decode("utf-8")
#按行分割浏览器请求生成列表
request_list = request_data.splitlines()
#浏览器的请求"GET / HTTP/1.1",通过正则表达式获取浏览器请求的文件路径
filename = ''
ret = re.match(r"[^/]+(/[^ ]*)",request_list[0])
if ret:
filename = ret.group(1)
if filename == '/':
filename = '/a.html'
print(filename)
#应答浏览器请求
try:
f = open("C:/Users/蓝坚/Desktop/a"+filename,"rb")
except:
response = "HTTP1.1 404 NOT FOUND\r\n"
response += "\r\n"
response += "-----404 NOT FOUND-----"
client_socket.send(response.encode("utf-8"))
else:
html_content = f.read()
f.close()
response = "HTTP1.1 200 OK\r\n"
response += "\r\n"
client_socket.sen