1、HTTP协议详解
参考文档:HTTP协议详解及使用
2、Python实现HTTP协议客户端
客户端(例如Web浏览器)向服务器发送HTTP请求。请求由请求行、请求头部和请求体组成。请求行包含请求方法(GET、POST等)、请求的URL和HTTP协议版本。
import socket
def send_http_request(host, port, request):
# 创建Socket连接
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
# 发送HTTP请求
client_socket.sendall(request.encode())
# 接收HTTP响应
response = b""
while True:
data = client_socket.recv(1024)
if not data:
break
response += data
# 关闭Socket连接
client_socket.close()
return response.decode()
# 定义HTTP请求报文
http_request = """GET / HTTP/1.1
Host: www.example.com
Connection: close
"""
# 发送HTTP请求并接收响应
response = send_http_request("www.example.com", 80, http_request)
print(response)
3、Python实现HTTP协议服务端
服务器接收处理请求,并将请求处理结果返回客户端。
import socket
def handle_http_request(request):
# 处理HTTP请求
response = "HTTP/1.1 200 OK\r\n"
response += "Content-Type: text/plain\r\n"
response += "\r\n"
response += "Hello, World!"
return response
# 创建Socket连接
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(1)
print("HTTP server is running at http://localhost:8080")
while True:
# 接受客户端连接
client_socket, client_address = server_socket.accept()
# 接收HTTP请求
request = client_socket.recv(1024).decode()
# 处理HTTP请求并生成响应
response = handle_http_request(request)
# 发送HTTP响应
client_socket.sendall(response.encode())
# 关闭客户端连接
client_socket.close()