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

运行 127.0.0.1 回环 TCP 单次收发、多客户端聊天室广播与布局/线程策略验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-socket1.py
explore-tutorial-socket1.py259 行
"""Offline verification lab for Android Ch 102: tutorial-socket1."""
import json
import socket
import threading
import xml.etree.ElementTree as ET

VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"

CHAT_LAYOUT_XML = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="简易聊天室" />
    <TextView
        android:id="@+id/txtshow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/editsend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btnsend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送" />
</LinearLayout>"""


def case_tcp_single_client_server_handshake():
    lines_received = []
    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(1)

        def server_worker():
            conn, _ = srv.accept()
            conn.settimeout(5)
            try:
                with conn.makefile("r", encoding="utf-8") as reader:
                    for line in reader:
                        lines_received.append(line.rstrip("\r\n"))
            finally:
                conn.close()

        t = threading.Thread(target=server_worker, daemon=True)
        t.start()

        cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        cli.settimeout(5)
        try:
            cli.connect(("127.0.0.1", port))
            cli.sendall("客户端:127.0.0.1 接入服务器\n".encode("utf-8"))
            cli.shutdown(socket.SHUT_WR)
        finally:
            cli.close()
        t.join(timeout=5)
    finally:
        srv.close()

    actual = {"received_lines": lines_received, "line_count": len(lines_received)}
    expected = {"received_lines": ["客户端:127.0.0.1 接入服务器"], "line_count": 1}
    return {
        "name": "tcp_single_client_server_handshake",
        "summary": "Verify single-connection TCP SocketServer accept, UTF-8 readLine, and shutdownOutput EOF",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_tcp_chatroom_broadcast_and_bye_leave():
    clients = []
    lock = threading.Lock()
    events = []
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.settimeout(5)

    def broadcast(msg: str):
        events.append(msg)
        data = (msg + "\n").encode("utf-8")
        with lock:
            targets = list(clients)
        for c in targets:
            try:
                c.sendall(data)
            except OSError:
                pass

    def handle_client(conn: socket.socket, cid: str):
        try:
            with conn.makefile("r", encoding="utf-8") as reader:
                for raw in reader:
                    text = raw.strip()
                    if text == "bye":
                        with lock:
                            if conn in clients:
                                clients.remove(conn)
                            online = len(clients)
                        broadcast(f"{cid}:leave:online={online}")
                        break
                    else:
                        broadcast(f"{cid}:say:{text}")
        finally:
            conn.close()

    threads = []
    try:
        srv.bind(("127.0.0.1", 0))
        port = srv.getsockname()[1]
        srv.listen(4)

        def accept_two():
            for cid in ("u1", "u2"):
                conn, _ = srv.accept()
                conn.settimeout(5)
                with lock:
                    clients.append(conn)
                    online = len(clients)
                broadcast(f"{cid}:join:online={online}")
                th = threading.Thread(target=handle_client, args=(conn, cid), daemon=True)
                threads.append(th)
                th.start()

        acc_t = threading.Thread(target=accept_two, daemon=True)
        acc_t.start()

        c1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        c2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        c1.settimeout(5)
        c2.settimeout(5)
        try:
            c1.connect(("127.0.0.1", port))
            r1 = c1.makefile("r", encoding="utf-8")
            join1 = r1.readline().strip()

            c2.connect(("127.0.0.1", port))
            r2 = c2.makefile("r", encoding="utf-8")
            join2_c1 = r1.readline().strip()
            join2_c2 = r2.readline().strip()

            c1.sendall("hello room\n".encode("utf-8"))
            say_c1 = r1.readline().strip()
            say_c2 = r2.readline().strip()

            c1.sendall("bye\n".encode("utf-8"))
            leave_c2 = r2.readline().strip()

            c2.sendall("bye\n".encode("utf-8"))
            r1.close()
            r2.close()
        finally:
            c1.close()
            c2.close()
        acc_t.join(timeout=5)
        for th in threads:
            th.join(timeout=5)
    finally:
        srv.close()

    actual = {
        "join1": join1,
        "join2_seen_by_both": [join2_c1, join2_c2],
        "broadcast_seen_by_both": [say_c1, say_c2],
        "u1_leave_seen_by_u2": leave_c2,
        "final_online": len(clients),
    }
    expected = {
        "join1": "u1:join:online=1",
        "join2_seen_by_both": ["u2:join:online=2", "u2:join:online=2"],
        "broadcast_seen_by_both": ["u1:say:hello room", "u1:say:hello room"],
        "u1_leave_seen_by_u2": "u1:leave:online=1",
        "final_online": 0,
    }
    return {
        "name": "tcp_chatroom_broadcast_and_bye_leave",
        "summary": "Verify multi-client TCP loopback chatroom broadcast and 'bye' disconnect removal",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_chat_layout_xml_verification():
    ns = "{http://schemas.android.com/apk/res/android}"
    root = ET.fromstring(CHAT_LAYOUT_XML)
    ids = [child.attrib.get(ns + "id") for child in root if (ns + "id") in child.attrib]
    actual = {
        "root_tag": root.tag,
        "orientation": root.attrib.get(ns + "orientation"),
        "child_count": len(list(root)),
        "widget_ids": ids,
    }
    expected = {
        "root_tag": "LinearLayout",
        "orientation": "vertical",
        "child_count": 4,
        "widget_ids": ["@+id/txtshow", "@+id/editsend", "@+id/btnsend"],
    }
    return {
        "name": "chat_layout_xml_verification",
        "summary": "Verify Android chatroom activity_main.xml LinearLayout structure and view IDs",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_android_main_thread_network_policy():
    handler_queue = []

    def simulate_dispatch(on_main_thread: bool, msg_what: int, text: str):
        if on_main_thread:
            return "NetworkOnMainThreadException"
        handler_queue.append((msg_what, text + "\n"))
        return "QUEUED_FOR_UI_HANDLER"

    res_main = simulate_dispatch(True, 0x123, "test")
    res_worker = simulate_dispatch(False, 0x123, "hello")
    actual = {
        "main_thread_network": res_main,
        "worker_thread_network": res_worker,
        "handler_messages": handler_queue,
    }
    expected = {
        "main_thread_network": "NetworkOnMainThreadException",
        "worker_thread_network": "QUEUED_FOR_UI_HANDLER",
        "handler_messages": [(0x123, "hello\n")],
    }
    return {
        "name": "android_main_thread_network_policy",
        "summary": "Verify Android main-thread network prohibition and worker-to-Handler UI update model",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_tcp_single_client_server_handshake(),
        case_tcp_chatroom_broadcast_and_bye_leave(),
        case_chat_layout_xml_verification(),
        case_android_main_thread_network_policy(),
    ]
    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-socket1-lab/explore-tutorial-socket1.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-socket1.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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