python源代码httpd.py:
#!/bin/env python3
from socket import *
import os
import signal
HOST = "0.0.0.0"
PORT = 80
MSG = """HTTP/1.1 200 OK
Content-Type: text/html
"""
MSG404 = """HTTP/1.1 404 NOT FOUND
Content-Type: text/html
<html>
<h1>
Sorry No Web Page for You!!!!
</h1>
</html>
"""
def handle( c):
while True:
bs = c.recv(1024)
if not bs:
break
data = bs.decode()
request = data.split('\n')[0]
print("request = ", request)
data = request.split()[1]
if data == "/":
with open("index.html") as f:
msg = MSG + f.read()
else:
filename = data.split("/")[1]
if os.path.exists(filename):
with open(filename) as f:
msg = MSG + f.read()
else:
msg = MSG404
c.send(msg.encode())
c.close()
print()
def server():
print("listen on port %d" % PORT)
sock = socket(AF_INET, SOCK_STREAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(5)
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
while True:
try:
c, addr = sock.accept()
print("connect from ", addr)
except KeyboardInterrupt:
os._exit(-1)
except Exception as e:
print(e)
continue
pid = os.fork()
if pid == 0:
sock.close()
handle(c)
os._exit(0)
elif pid > 0:
c.close()
else:
pass
if __name__ == "__main__":
server()
在与httpd.py相同目录下准备两个html文件:index.html和c1.html
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome index</title>
</head>
<body>
<h1></h1>
<div>
<p>
This is a Test Page
</p>
</div>
</body>
</html>
<!--c1.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试网页c1</title>
</head>
<style>
div {
font-size:20px;
color: blue;
}
</style>
<body>
<div >
<h1>锦瑟</h1>
<p style="font-size:25px">锦瑟无端五十弦,一弦一柱思华年。</p>
<p style="color:red">庄生晓梦迷蝴蝶,望帝春心托杜鹃。</p>
<p>沧海月明珠有泪,蓝田日暖玉生烟。</p>
<p>此情可待成追忆,只是当时已惘然。</p>
</div>
</body>
</html>
客户端测试:
运行httpd.py
测试浏览器chrome:分别访问index.html, c1.html以及一个不存在的abc.html,结果如下:
服务器端连接信息:
[root@gyl-ali python3]# ./httpd.py
listen on port 80
connect from ('61.87.242.101', 63505)
connect from ('61.87.242.101', 63506)
request = GET /abc.html HTTP/1.1
request = GET /index.html HTTP/1.1
connect from ('61.87.242.101', 63588)
request = GET /c1.html HTTP/1.1