返回固定页面的Http服务器
import socket
def service_client(new_socket):
"""为这个客户端返回数据"""
# 1. 接收浏览器发送过来的请求,即http请求
# GET / HTTP 1.1
request = new_socket.recvfrom(1024)
print(request)
# 2. 返回http格式的数据,给浏览器
# 2.1 准备发送给浏览器的数据---header
response = "HTTP/1.1 200 OK\r\n" # 换行
response += "\r\n"
# 2.2 准备发送给浏览器的数据---body
response += "<h1>hello world</h1>"
new_socket.send(response.encode("utf-8"))
# 3. 关闭套接字
new_socket.close()
def main():
# 1. 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置当服务器先close 即服务器端4次挥手之后资源能够立即释放,这样就保证了下次运行的时候可以立即使用这个地址
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
# 2. 绑定
tcp_server_socket.bind(("127.0.0.1", 7890))
# 3. 变为监听套接字
tcp_server_socket.listen(128)
# 4. 等待新客户的链接
new_socket, client_addr = tcp_server_socket.accept()
# 5. 为这个客户端服务
service_client(new_socket)
if __name__ == '__main__':
main()
tcp的3次握手和4次挥手
3次握手.png4次挥手.png
Http服务器返回客户端相应网页
import socket
import re
def service_client(new_socket):
"""为这个客户端返回数据"""
# 1. 接收浏览器发送过来的请求,即http请求
# GET / HTTP 1.1
request = new_socket.recv(1024).decode("utf-8 ")
# print(">" * 50)
# print(request)
requet_lines = request.splitlines()
print("")
print(">" * 20)
print(requet_lines)
# GET /index.html HTTP/1.1
file_name = ""
# [ ]的^ 表示取反 即不是/ 不是空格
ret = re.match(r"[^/]+(/[^ ]*)", requet_lines[0])
print("-" * 100)
print(ret)
print("-" * 100)
if ret:
file_name = ret.group(1)
# print("*" * 50, file_name)
if file_name == "/":
file_name = "/index.html"
try:
f = open("./html" + file_name, "rb")
except:
response = "HTTP/1.1 404 NOT FOUND\r\n" # 换行
response += "\r\n"
response += "---file not found---"
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" # 换行
response += "\r\n"
# 2.2 准备发送给浏览器的数据---body
# response += "<h1>hello world</h1>"
# new_socket.send(response.encode("utf-8"))
# 将response header发送给浏览器
new_socket.send(response.encode("utf-8"))
# 将response body发送给浏览器
new_socket.send(html_content)
# 3. 关闭套接字
new_socket.close()
def main():
# 1. 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置当服务器先close 即服务器端4次挥手之后资源能够立即释放,这样就保证了下次运行的时候可以立即使用这个地址
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
# 2. 绑定
tcp_server_socket.bind(("127.0.0.1", 7890))
# 3. 变为监听套接字
tcp_server_socket.listen(128)
while True:
# 4. 等待新客户的链接
new_socket, client_addr = tcp_server_socket.accept()
# 5. 为这个客户端服务
service_client(new_socket)
if __name__ == '__main__':
main()
网友评论