import socket
import threading
import sys
"""
使用socket自定义HttpServer
"""
class HttpServer:
def __init__(self,port, **kwargs):
self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#socket 函数创建套接字
self._server.bind(("localhost", port))#绑定地址(host,port)到套接字
self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#设定给定套接字选项的值
self._server.listen(128)#开始TCP监听
print(f"服务启动,访问地址为: localhost:{port}")
@staticmethod
def handle_request(client_socket, address):
recv_data = client_socket.recv(1024)#接收TCP数据,数据以字符串形式返回
if len(recv_data) == 0:#接收不到数据显示即将关闭
print(f'{address}即将关闭!')
client_socket.close()
return
r_data = recv_data.decode("utf8")
print(f'r_date 接收到数据是{r_data}')
# 解析数据
headers = r_data.split(" ", maxsplit=2) # 截取最前面的一行(消息头) GET /ac HTTP/1.1
print(headers)
url = headers[1]
print(f'url 的内容是:{url}')
# 根据url返回信息
if "/go" == url:
send_data = ""
# 读取页面
with open('welcome.html','rb') as f:
send_temp_data = f.read().decode("utf8")
# 渲染模板
send_data = send_temp_data.replace("{{content}}", address[0])
else:
send_data = ""
# 读取页面
with open('other.html','rb') as f:
send_data = f.read().decode("utf8")
# 响应数据
# 拼接响应头
resp_line = "HTTP/1.1 200 OK\r\n"
resp_head = "Server: PWS1.0\r\n"
client_socket.send((resp_line+ resp_head + "\r\n").encode("utf8") +send_data.encode("utf8"))
client_socket.close()
def start(self):
while True:
client_socket,address = self._server.accept()
print(f'server accept接收到的socket 和 adress是:{client_socket}##{address}')
t = threading.Thread(group=None, target=self.handle_request, args=(client_socket, address))
t.setDaemon(True)
t.start()
def stop(self):
self._server.close()
def main():
# 验证参数
# 若使用 python xxx.py 8080 命令,那么argv[0] = xxx.py, argv[1] = 8080
# print(sys.argv)
args = sys.argv
print(args)
if len(args) != 2:
print("参数有误,需要格式为 python HttpServer.py 8080")
return
# 判断字符串是否都是数字组成
if not sys.argv[1].isdigit():
print("执行命令如下: python HttpServer.py 8080")
return
# 获取端口号
port = int(sys.argv[1])
try:
server = HttpServer(port=port)
server.start()
except KeyboardInterrupt:
server.stop()
if __name__ == '__main__':
main()
同名文件加下还需要下面两个HTML文件
welcome.html
<!-- welcome.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Welcome your visit!</h1>
<h1>{{content}}</h1>
</body>
</html>
other.html
<!-- welcome.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Welcome your visit!</h1>
<h1>{{content}}</h1>
</body>
</html>
运行时在Thermal窗口输入python TCPIPserver.py 8080
在web中输入localhost:8080/go 那么localhost的地址就出来了
输入localhost:8080/go1 那么就出现{{content}}