基于Python实现一个简单的HttpServer,当用户在浏览器中输入IP地址:8000时,则会返回index.html页面内容,访问其它信息,则会返回错误信息(404)
"""
httpserver v1.0
1.获取来自浏览器的请求,
2.判断如果请求内容是 / ,就将index.html返回给客户端
3.如果请求是其它内容则返回404
"""
from socket import *
def request(connfd):
data = connfd.recv(4096)
if not data:
return
content = data.decode()
listcon = content.split("\r\n")
reqinfo = listcon[0].split(" ")[1]
print(reqinfo)
if reqinfo == "/":
with open("index.html") as f:
response = "HTTP/1.1 200 OK\r\n"
response += "Content-Type:text/html\r\n"
response += "\r\n"
response += f.read()
print(response)
else:
response = "HTTP/1.1 404 Not Found\r\n"
response += "Content-Type:text/html\r\n"
response += "\r\n"
response += "Sorry .....\r\n"
connfd.send(response.encode())
sockfd = socket()
sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sockfd.bind(('0.0.0.0', 8000))
sockfd.listen(3)
while True:
connfd, addr = sockfd.accept()
request(connfd)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>人生在世,好好努力title>
head>
<body>
好好努力吧,少年
body>
html>
~