文章目录
- 1.http 客户端-RPC客户端
- 1.http 服务端-RPC服务端
- 3.WireShark抓包分析
- 3.1客户端到服务端的HTTP/JSON报文
- 3.2服务端到客户端的HTTP/JSON报文
1.http 客户端-RPC客户端
import json
import requests
class RPCClient:def __init__(self, server_url):self.server_url = server_urldef call(self, method, params):request_data = {'method': method,'params': params,'id': 1}json_data = json.dumps(request_data).encode('utf-8')response = requests.post(self.server_url, json_data, headers={'Content-type': 'application/json'})result = response.json()if 'error' in result:raise Exception(result['error'])return result['result']
client = RPCClient('http://192.168.1.9:8000')
result = client.call('add', [3, 5])
print("Result:", result)
1.http 服务端-RPC服务端
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class RPCHandler(BaseHTTPRequestHandler):def do_POST(self):content_length = int(self.headers['Content-Length'])json_data = self.rfile.read(content_length).decode('utf-8')print("-------json_data:{}".format(json_data))data = json.loads(json_data)print("-------data:{}".format(data))result = self.process_request(data)self.send_response(200)self.send_header('Content-type', 'application/json')self.end_headers()print(json.dumps(result).encode('utf-8'))self.wfile.write(json.dumps(result).encode('utf-8'))def process_request(self, data):if 'method' in data:method = data['method']if method == 'add':if 'params' in data and len(data['params']) == 2:a, b = data['params']result = a + breturn {'result': result}return {'error': 'Invalid request'}
def run_server():port = 8000server_address = ('192.168.1.9', port)httpd = HTTPServer(server_address, RPCHandler)httpd.serve_forever()if __name__ == '__main__':run_server()
3.WireShark抓包分析
3.1客户端到服务端的HTTP/JSON报文
3.2服务端到客户端的HTTP/JSON报文