蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

TCP/IP 协议参考:职责、层次和历史技术:独立实测

PYTHONPython 3.12;本机回环socket、HTTP或标准库序列化protocols.py
protocols.py18 行
"""Owned local HTTP/1.1 exchange; no TLS or public DNS claim."""
from http.server import ThreadingHTTPServer,BaseHTTPRequestHandler
from http.client import HTTPConnection
import threading,json
BODY=json.dumps({'site':'蓝色天空网','domain':'mbsky.com','lesson':'应用层与传输层分开核对'},ensure_ascii=False).encode('utf-8')
class Handler(BaseHTTPRequestHandler):
 protocol_version='HTTP/1.1'
 def do_GET(self):
  if self.path!='/lesson':self.send_error(404);return
  self.send_response(200);self.send_header('Content-Type','application/json; charset=utf-8');self.send_header('Content-Length',str(len(BODY)));self.end_headers();self.wfile.write(BODY)
 def log_message(self,*args):pass
server=ThreadingHTTPServer(('127.0.0.1',0),Handler);thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
client=HTTPConnection('127.0.0.1',server.server_port,timeout=5)
try:
 client.request('GET','/lesson');response=client.getresponse();raw=response.read();data=json.loads(raw);assert response.status==200 and data['domain']=='mbsky.com';assert len(raw)==int(response.getheader('Content-Length'))
 print(json.dumps({'status':response.status,'content_type':response.getheader('Content-Type'),'body':data,'scope':'local HTTP/1.1 over TCP; TLS, HTTP/2 and HTTP/3 not observed'},ensure_ascii=False))
finally:client.close();server.shutdown();server.server_close();thread.join(5)
本例需在 Python 3.12;本机回环socket、HTTP或标准库序列化 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12;本机回环socket、HTTP或标准库序列化

入口文件:projects/tcpip-lab/protocols.py

预期结果与验证条件观察提示
  • status=200
  • 正文domain=mbsky.com
  • Content-Length与实际字节数一致

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:TCP/IP

课程关联工程包(登记关联5章) · 含当前章节或实例 · mbskycom202611a444.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习