代码
import socket
#导入套接字
import re
import multiprocessing
def server_client(new_socket):
# 为客户端返回数据
#1、接收浏览器发送过来的请求,即http请求
#GET / HTTP / 1.1
#......
request = new_socket.recv(1024).decode('utf-8')
# print(request)
request_lines = request.splitlines()
print('')
print('>' * 20)
print(request_lines)
# get post put del
ret = re.match(r'[^/]+(/[^ ]*)',request_lines[0])
file_name = ''
#除了/之外,匹配一个或多个,往后匹配,只要不是空格
#就要,是空格就停
if ret:
file_name = ret.group(1)
#匹配的是,小括号里面的
print("*"* 50,file_name)
if file_name == '/':
file_name = '/index.html'
try:
# f = open('../项目备份/index.html','rb')
f = open('../项目备份/index.html'+file_name, 'rb')
except:
response = 'HTTP/1.1 404 not fonund \r\n' # \r\n 是为了兼容Windows
response += '\r\n'
response += '--file not find--'
new_socket.send(response.encode('utf-8'))
else:
html_content = f.read()
f.close()
# 2、返回http格式的数据给浏览器
# 2.1 准备发送给浏览器的header
response = 'HTTP/1.1 200 OK \r\n' # \r\n 是为了兼容Windows
response += '\r\n'
# 2.2准备发送给浏览器的body
# response+= '<h1>haha
#将Response Header 发送给浏览器
new_socket.send(response.encode('utf-8'))
#将Response Body发送给浏览器
new_socket.send(html_content)
#关闭客户端的套接字
new_socket.close()
def main():
# 用来完成整体的控制
#1、创建套接字
tcp_sever_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_sever_socket .setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#如果不想让客户端先发送关闭请求的话
#2、绑定
tcp_sever_socket.bind(('',7890))#里面的小括号为元祖
#3、变为监听套接字(最大链接数128)
tcp_sever_socket.listen(128)#128表示同时为128个客户端同时服务
while True:
#4、等待新客户端的链接
new_socket,client_addr = tcp_sever_socket.accept()
#5、为这个客户端服务
# server_client(new_socket)
p = multiprocessing.process(target = server_client,args = (new_socket,))
p.start()
new_socket.close()
#6、关闭监听套接字
tcp_sever_socket.close()
if __name__ == '__main__':
main()
网友评论