#__author: han-zhang
#date: 2019/1/5 11:30
import socket
import re
def request_handers(client_socket,client_addr):
print(client_addr,"连接 success")
#接受客户端请求
recv_data=client_socket.recv(1024).decode("utf-8")
# print(type(recv_data))
#以行分割请求头信息
client_request_headers = recv_data.splitlines()
#循环遍历行信息并打印
for line in client_request_headers:
print(line)
#判断客户端行为
http_request_headers = client_request_headers[0]
print(http_request_headers)
#GET / HTTP/1.1
#GET /login HTTP/1.1
file_name = re.match(r"[^/]+(/[^ ]*) ",http_request_headers).group(1)
print(file_name)
#判断请求内容
if file_name == "/":
new_file_name = "/index.html"
else:
#.html市演示过程创建的,正常服务器中请慎重
new_file_name = "file_name"
#尝试发送
try:
f = open(new_file_name,'rb')
except:
#页面不存在
response_headers = "HTTP/ 404 not found\n\r"
response_headers += "\n\r"
response_body = '''
Snow
(February 1936)
North country scene:
A hundred leagues locked in ice,
A thousand leagues of whirling snow.
Both side of the Great Wall
One single white immensity.
The Yellow River's swift current
Is stilled from end to end.
The mountains dance silver snakes
And the highland charge like wax-hued elephants.
Vying with heaven in stature.
On a fine day, the land,
Clad in white, adorned in red,
Crows more enchanting.
This land so rich in beauty
Has made countless heroes bow in homage.
But alas! Qin Shihuang and Han Wudi
Were lacking in literary grace,
And Tang Taizong and Song Taizu
Had little poetry in their souls;
That proud son of Heaven,
Genghis Khan,
Knew only shooting eagles, bow outstretched.
All are past and gone!
For truly great men
Look to this age alone.
'''
else:
#页面存在
response_headers = "HTTP/ 200 OK\r\n"
response_headers += "\r\n"
response_body = f.read()
finally:
client_socket.sendall(response_headers.encode('utf-8'))
client_socket.sendall(response_body.encode('utf-8'))
client_socket.close()
def main():
#实例化套接字
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定地址端口
server_socket.bind(("localhost",8000))
#监听
server_socket.listen(10)
while True:
#会话阻塞
client_socket, client_addr =server_socket.accept()
request_handers(client_socket, client_addr)
if __name__ == "__main__":
main()
未经笔者允许,不得转载