7.6.2 基于 TCP 协议的 Socket 通信(1)
讲解 TCP Socket 通信四步模型、Java ServerSocket 服务端与 Android 客户端实现,以及基于线程池和 Handler 的多客户端简易聊天室。
学完这一章,你能够
- 讲解 TCP Socket 通信四步模型、Java ServerSocket 服务端与 Android 客户端实现,以及基于线程池和 Handler 的多客户端简易聊天室。
Socket 概念与 TCP 通信四步模型
基于 TCP 的 Socket 通信采用经典的客户端/服务端(C/S)字节流模型。完整交互可概括为四个步骤:首先分别创建服务端监听套接字 `ServerSocket` 与客户端 `Socket`;其次连接建立后打开双方关联的输入流与输出流;接着按约定协议执行读写操作;最后依次关闭流对象与 Socket 连接释放系统描述符。
TCP 服务端与 Android 客户端单次通信
编写 TCP 服务端 `SocketServer` 需按五步推进:绑定端口(如 `12345`)创建 `ServerSocket`;阻塞调用 `accept()` 等待客户端接入;连接后经 `getInputStream()` 包装 `InputStreamReader(..., "UTF-8")` 与 `BufferedReader` 循环 `readLine()` 读取文本;需要回复时通过输出流写回响应;最后调用 `shutdownInput()` 并关闭 `Socket`(实际工程还应在 `finally` 中关闭 `ServerSocket` 与流)。
Android 客户端则以目标服务器 IP 与端口构造 `Socket`,经 `getOutputStream()` 与 `PrintWriter` 写入消息并 `flush()`,随后 `shutdownOutput()` 通知服务端输入结束并关闭连接。需要特别注意:自 Android 4.0 起系统禁止在主线程(UI 线程)执行网络 I/O(否则触发 `NetworkOnMainThreadException`),因此必须在 `onClick` 中另起子线程执行 `acceptServer()`。本站离线实验在 `127.0.0.1` 回环地址上实测了真实单次 TCP 连接、UTF-8 换行读取与半关闭 `SHUT_WR` 触发 EOF。
进阶案例:线程池多客户端 TCP 聊天室
为支持多客户端实时互发消息,服务端 `Server` 维护在线连接集合 `List<Socket>`(高并发工程中建议使用线程安全集合如 `CopyOnWriteArrayList` 或加锁同步)与线程池 `Executors.newCachedThreadPool()`。主循环持续调用 `server.accept()`,每接入新客户端便将其加入集合并提交 `Service` 任务线程;任务线程循环读取每行消息并遍历集合向所有在线客户端广播,当收到 `"bye"` 时将该连接从集合移除、关闭资源并广播下线通知。
Android 聊天客户端界面 `activity_main.xml` 采用纵向 `LinearLayout`,依次摆放标题、消息展示 `TextView`(`txtshow`)、输入框 `EditText`(`editsend`)与发送按钮 `Button`(`btnsend`)。`MainActivity` 在工作线程中建立 `Socket` 连接与循环读取服务端推送行,再通过 `Handler` 发送 `what=0x123` 消息回到主线程追加到 `StringBuilder` 刷新界面。注意实际开发中也不应在点击事件的主线程直接执行 `out.println(msg)` 网络写入,且应将连接初始化与读线程同步以免未连接前空指针异常。本站实验在本地回环地址实测了两客户端加入、全员广播及 `bye` 退出后在线人数归零的完整流程。
运行 127.0.0.1 回环 TCP 单次收发、多客户端聊天室广播与布局/线程策略验证
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
Android 禁止在 UI 主线程执行阻塞网络操作以防界面卡顿(会抛出 NetworkOnMainThreadException),而 UI 控件又是非线程安全的,不能在子线程直接修改,因此需在子线程收发 Socket 并通过 Handler 切回主线程刷新界面。