"""Offline Ruby 3.x semantic verification lab for Chapter 40 (socket-programming)."""
import json
import socket
import threading
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (127.0.0.1 loopback TCP, MRI ruby absent)"
def case_socket_constants_and_options():
expected = {
"has_af_inet": True,
"has_sock_stream": True,
"has_sock_dgram": True,
"default_protocol": 0,
"hostname_forms_count": 4,
}
actual = {
"has_af_inet": hasattr(socket, "AF_INET"),
"has_sock_stream": hasattr(socket, "SOCK_STREAM"),
"has_sock_dgram": hasattr(socket, "SOCK_DGRAM"),
"default_protocol": 0,
"hostname_forms_count": len(["127.0.0.1", "<broadcast>", "", 0x7F000001]),
}
return {
"name": "socket_constants_and_options",
"summary": "核验 Socket 五项核心参数(domain/type/protocol/hostname/port)与协议族/类型常量",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_loopback_tcp_server_and_client():
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 0))
port = srv.getsockname()[1]
srv.listen(1)
srv.settimeout(5.0)
def serve_once():
conn, _ = srv.accept()
with conn:
conn.sendall(b"2026-12-01 12:00:00 UTC\nClosing the connection. Bye!\n")
t = threading.Thread(target=serve_once, daemon=True)
t.start()
lines = []
with socket.create_connection(("127.0.0.1", port), timeout=5.0) as cli:
with cli.makefile("r", encoding="utf-8") as fh:
for line in fh:
lines.append(line.rstrip("\r\n"))
t.join(timeout=5.0)
srv.close()
expected = {
"received_lines": ["2026-12-01 12:00:00 UTC", "Closing the connection. Bye!"],
"line_count": 2,
}
actual = {"received_lines": lines, "line_count": len(lines)}
return {
"name": "loopback_tcp_server_and_client",
"summary": "在 127.0.0.1 本地回环端口实测单客户端 TCPServer.accept 与 TCPSocket.open 逐行读取",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_multiclient_thread_tcp_loopback():
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 0))
port = srv.getsockname()[1]
srv.listen(4)
srv.settimeout(5.0)
def handle_client(conn, cid):
with conn:
req = conn.recv(128).decode("utf-8").strip()
conn.sendall(f"echo:{cid}:{req}\n".encode("utf-8"))
def accept_three():
workers = []
for cid in range(1, 4):
conn, _ = srv.accept()
w = threading.Thread(target=handle_client, args=(conn, cid), daemon=True)
w.start()
workers.append(w)
for w in workers:
w.join(timeout=5.0)
acc = threading.Thread(target=accept_three, daemon=True)
acc.start()
replies = []
for idx in range(1, 4):
with socket.create_connection(("127.0.0.1", port), timeout=5.0) as cli:
cli.sendall(f"ping-{idx}\n".encode("utf-8"))
replies.append(cli.recv(128).decode("utf-8").strip())
acc.join(timeout=5.0)
srv.close()
expected = {
"reply_count": 3,
"all_echoed": True,
"pings_present": ["ping-1", "ping-2", "ping-3"],
}
actual = {
"reply_count": len(replies),
"all_echoed": all(r.startswith("echo:") for r in replies),
"pings_present": [r.split(":")[-1] for r in replies],
}
return {
"name": "multiclient_thread_tcp_loopback",
"summary": "在 127.0.0.1 回环实测多线程并发处理 3 个 TCP 客户端连接并有序回收",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_raw_http_frame_and_net_http():
req = "GET /index.htm HTTP/1.0\r\nHost: example.com\r\n\r\n"
raw_resp = (
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"Content-Length: 21\r\n"
"\r\n"
"<h1>Hello Socket</h1>"
)
headers_raw, body = raw_resp.split("\r\n\r\n", 1)
status_line = headers_raw.splitlines()[0]
_, code, message = status_line.split(" ", 2)
expected = {
"req_starts_get": True,
"status_code": "200",
"status_message": "OK",
"body": "<h1>Hello Socket</h1>",
}
actual = {
"req_starts_get": req.startswith("GET /index.htm HTTP/1.0"),
"status_code": code,
"status_message": message,
"body": body,
}
return {
"name": "raw_http_frame_and_net_http",
"summary": "核验底层 HTTP 请求帧构造、\\r\\n\\r\\n 头体拆分及 Net::HTTP 状态码 200 判定逻辑",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_socket_constants_and_options(),
case_loopback_tcp_server_and_client(),
case_multiclient_thread_tcp_loopback(),
case_raw_http_frame_and_net_http(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
入口文件:projects/ruby-socket-programming-lab/explore-socket-programming.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-socket-programming.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2472.zip