使用 Python 分别完成客户端和服务端内容,您可以使用标准库中的 http.server 模块来创建一个简单的 HTTP 服务器,并使用 http.clientrequests 库来创建一个客户端。以下是一个简单的示例:

首先,创建一个服务器端(服务端)的 Python 脚本 server.py

from http.server import BaseHTTPRequestHandler, HTTPServer

# 创建自定义的请求处理类,继承自 BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
    # 处理 GET 请求
    def do_GET(self):
        self.send_response(200)  # 设置响应状态码
        self.send_header('Content-type', 'text/html')  # 设置响应头部信息
        self.end_headers()
        self.wfile.write(b'Hello, World!')  # 发送响应内容

# 启动服务器
def run():
    server_address = ('', 8000)  # 设置服务器地址和端口
    httpd = HTTPServer(server_address, MyHandler)  # 创建 HTTPServer 实例
    print('Starting server...')
    httpd.serve_forever()  # 启动服务器

run()

接下来,创建一个客户端的 Python 脚本 client.py

使用 http.client 库:

import http.client

conn = http.client.HTTPConnection('localhost', 8000)  # 创建连接
conn.request('GET', '/')  # 发送 GET 请求
response = conn.getresponse()  # 获取响应
print(response.status, response.reason)  # 打印响应状态码和状态信息
data = response.read()  # 读取响应内容
print(data.decode())  # 打印响应内容
conn.close()  # 关闭连接

或者使用 requests 库:

import requests

response = requests.get('http://localhost:8000')  # 发送 GET 请求
print(response.status_code)  # 打印响应状态码
print(response.text)  # 打印响应内容

在运行这两个脚本之前,先在终端中分别执行 python server.pypython client.py,分别启动服务器和客户端。然后你会看到客户端发送请求给服务器,并打印出服务器返回的响应内容。

Python 客户端和服务器端通信示例:使用 http.server 和 requests 库

原文地址: https://www.cveoy.top/t/topic/XKz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录