"""Offline verification lab for Android Ch 103: tutorial-socket2."""
import hashlib
import io
import json
import socket
import sqlite3
import tempfile
import threading
import xml.etree.ElementTree as ET
from pathlib import Path
VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"
CLIENT_LAYOUT_XML = """<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="文件名" android:textSize="18sp" />
<EditText android:id="@+id/edit_fname" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="sample.mp3" />
<Button android:id="@+id/btn_upload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上传" />
<Button android:id="@+id/btn_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止" />
<ProgressBar android:id="@+id/pgbar" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="fill_parent" android:layout_height="40px" />
<TextView android:id="@+id/txt_result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" />
</LinearLayout>"""
MANIFEST_PERMISSIONS_XML = """<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>"""
def read_protocol_line(stream: io.BufferedReader):
buf = bytearray()
while True:
b = stream.read(1)
if not b:
return None if not buf else buf.decode("utf-8")
if b == b"\n":
break
if b == b"\r":
nxt = stream.peek(1)[:1]
if nxt == b"\n":
stream.read(1)
break
buf.extend(b)
return buf.decode("utf-8")
def case_stream_tool_readline_crlf_and_chunk_read():
raw = io.BufferedReader(io.BytesIO(b"line1\r\nline2\rline3\nline4"))
lines = []
while True:
ln = read_protocol_line(raw)
if ln is None:
break
lines.append(ln)
chunk_src = io.BytesIO(b"A" * 2500)
chunks = 0
total = 0
while True:
part = chunk_src.read(1024)
if not part:
break
chunks += 1
total += len(part)
actual = {"lines": lines, "chunk_reads": chunks, "total_bytes": total}
expected = {"lines": ["line1", "line2", "line3", "line4"], "chunk_reads": 3, "total_bytes": 2500}
return {
"name": "stream_tool_readline_crlf_and_chunk_read",
"summary": "Verify PushbackInputStream-style CRLF/CR/LF readLine and 1024B chunk stream reads",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_tcp_resumable_upload_protocol_interrupted_and_resumed():
payload = bytes((i * 31 + 17) % 256 for i in range(7500))
orig_sha = hashlib.sha256(payload).hexdigest()
first_chunk_limit = 3072
with tempfile.TemporaryDirectory() as tmp:
tp = Path(tmp)
src_file = tp / "audio_sample.bin"
src_file.write_bytes(payload)
srv_dir = tp / "server_files"
srv_dir.mkdir()
records = {}
next_id = [10001]
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.settimeout(5)
try:
srv.bind(("127.0.0.1", 0))
port = srv.getsockname()[1]
srv.listen(4)
def serve_connections():
for _ in range(2):
conn, _ = srv.accept()
conn.settimeout(5)
try:
rfile = conn.makefile("rb")
head = read_protocol_line(rfile)
kv = dict(item.split("=", 1) for item in head.split(";"))
file_len = int(kv["Content-Length"])
fname = kv["filename"]
sid_str = kv["sourceid"]
if sid_str and int(sid_str) in records:
sid = int(sid_str)
dest = records[sid]
log_path = dest.with_name(dest.name + ".log")
pos = int(log_path.read_text(encoding="utf-8").split("=")[1].strip())
else:
sid = next_id[0]
next_id[0] += 1
dest = srv_dir / fname
records[sid] = dest
pos = 0
conn.sendall(f"sourceid={sid};position={pos}\r\n".encode("utf-8"))
mode = "r+b" if dest.exists() else "w+b"
with open(dest, mode) as fout:
if pos == 0:
fout.truncate(file_len)
fout.seek(pos)
written = pos
while True:
chunk = rfile.read(1024)
if not chunk:
break
fout.write(chunk)
written += len(chunk)
dest.with_name(dest.name + ".log").write_text(f"length={written}\n", encoding="utf-8")
if written == file_len:
records.pop(sid, None)
rfile.close()
finally:
conn.close()
st = threading.Thread(target=serve_connections, daemon=True)
st.start()
# Phase 1: upload 3072 bytes then stop
c1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c1.settimeout(5)
try:
c1.connect(("127.0.0.1", port))
c1.sendall(f"Content-Length={len(payload)};filename=audio_sample.bin;sourceid=\r\n".encode("utf-8"))
r1 = c1.makefile("rb")
resp1 = read_protocol_line(r1)
r1.close()
p1 = dict(item.split("=", 1) for item in resp1.split(";"))
assigned_sid = p1["sourceid"]
pos1 = int(p1["position"])
with open(src_file, "rb") as fin:
fin.seek(pos1)
c1.sendall(fin.read(first_chunk_limit))
c1.shutdown(socket.SHUT_WR)
finally:
c1.close()
# Phase 2: resume from server-reported position
c2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c2.settimeout(5)
try:
c2.connect(("127.0.0.1", port))
c2.sendall(
f"Content-Length={len(payload)};filename=audio_sample.bin;sourceid={assigned_sid}\r\n".encode("utf-8")
)
r2 = c2.makefile("rb")
resp2 = read_protocol_line(r2)
r2.close()
p2 = dict(item.split("=", 1) for item in resp2.split(";"))
pos2 = int(p2["position"])
with open(src_file, "rb") as fin:
fin.seek(pos2)
c2.sendall(fin.read())
c2.shutdown(socket.SHUT_WR)
finally:
c2.close()
st.join(timeout=5)
uploaded_file = srv_dir / "audio_sample.bin"
uploaded_sha = hashlib.sha256(uploaded_file.read_bytes()).hexdigest()
log_final = (srv_dir / "audio_sample.bin.log").read_text(encoding="utf-8").strip()
remaining_records = len(records)
finally:
srv.close()
actual = {
"phase1_position": pos1,
"phase2_resume_position": pos2,
"sha256_match": uploaded_sha == orig_sha,
"final_log": log_final,
"server_records_cleaned": remaining_records == 0,
}
expected = {
"phase1_position": 0,
"phase2_resume_position": 3072,
"sha256_match": True,
"final_log": "length=7500",
"server_records_cleaned": True,
}
return {
"name": "tcp_resumable_upload_protocol_interrupted_and_resumed",
"summary": "Verify real 127.0.0.1 loopback TCP resumable file upload with interruption at 3072B and resume to 7500B",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_sqlite_uploadlog_persistence():
conn = sqlite3.connect(":memory:")
try:
conn.execute(
"CREATE TABLE IF NOT EXISTS uploadlog (_id integer primary key autoincrement, path varchar(20), sourceid varchar(20))"
)
fpath = "/sdcard/sample.mp3"
before = conn.execute("select sourceid from uploadlog where path=?", (fpath,)).fetchone()
conn.execute("insert into uploadlog(path,sourceid) values(?,?)", (fpath, "10001"))
saved = conn.execute("select sourceid from uploadlog where path=?", (fpath,)).fetchone()
conn.execute("delete from uploadlog where path=?", (fpath,))
after = conn.execute("select sourceid from uploadlog where path=?", (fpath,)).fetchone()
finally:
conn.close()
actual = {
"before_save": before,
"after_save": saved[0] if saved else None,
"after_complete_delete": after,
}
expected = {
"before_save": None,
"after_save": "10001",
"after_complete_delete": None,
}
return {
"name": "sqlite_uploadlog_persistence",
"summary": "Verify UploadHelper SQLite uploadlog table save, getBindId, and delete lifecycle",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_client_layout_and_manifest_permissions():
ns = "{http://schemas.android.com/apk/res/android}"
layout_root = ET.fromstring(CLIENT_LAYOUT_XML)
ids = [c.attrib[ns + "id"] for c in layout_root if (ns + "id") in c.attrib]
manifest_root = ET.fromstring(MANIFEST_PERMISSIONS_XML)
perms = [c.attrib[ns + "name"] for c in manifest_root.findall("uses-permission")]
actual = {"widget_ids": ids, "permissions": perms}
expected = {
"widget_ids": ["@+id/edit_fname", "@+id/btn_upload", "@+id/btn_stop", "@+id/pgbar", "@+id/txt_result"],
"permissions": [
"android.permission.MOUNT_UNMOUNT_FILESYSTEMS",
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.INTERNET",
],
}
return {
"name": "client_layout_and_manifest_permissions",
"summary": "Verify resumable upload layout IDs and AndroidManifest permissions",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_stream_tool_readline_crlf_and_chunk_read(),
case_tcp_resumable_upload_protocol_interrupted_and_resumed(),
case_sqlite_uploadlog_persistence(),
case_client_layout_and_manifest_permissions(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-socket2-lab/explore-tutorial-socket2.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-socket2.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1950.zip