示例工程 31-io-files-struct-socket-sqlite
31-io-files-struct-socket-sqlite/04-tcp-length-prefix/tcp_length_prefix.py
"""TCP 长度前缀:用 4 字节大端长度解决粘包。"""
from __future__ import annotations
import socket
import struct
import threading
def send_message(sock: socket.socket, text: str) -> None:
payload = text.encode("utf-8")
sock.sendall(struct.pack("!I", len(payload)) + payload)
def recv_exact(sock: socket.socket, size: int) -> bytes:
chunks: list[bytes] = []
remaining = size
while remaining:
chunk = sock.recv(remaining)
if not chunk:
raise ConnectionError("connection closed")
chunks.append(chunk)
remaining -= len(chunk)
return b"".join(chunks)
def recv_message(sock: socket.socket) -> str:
length = struct.unpack("!I", recv_exact(sock, 4))[0]
return recv_exact(sock, length).decode("utf-8")
def roundtrip(messages: list[str]) -> list[str]:
ready = threading.Event()
ports: list[int] = []
received: list[str] = []
errors: list[BaseException] = []
def server() -> None:
try:
with socket.socket() as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
ports.append(listener.getsockname()[1])
ready.set()
conn, _ = listener.accept()
with conn:
conn.settimeout(2)
for _ in messages:
received.append(recv_message(conn))
except BaseException as exc:
errors.append(exc)
finally:
ready.set()
thread = threading.Thread(target=server)
thread.start()
if not ready.wait(timeout=2) or not ports:
raise TimeoutError("server failed to start")
with socket.create_connection(("127.0.0.1", ports[0]), timeout=2) as client:
for message in messages:
send_message(client, message)
thread.join(timeout=2)
if errors:
raise errors[0]
if thread.is_alive():
raise TimeoutError("server did not finish")
return received
def main() -> None:
messages = ["你好", "second"]
print(f"received: {roundtrip(messages)}")
if __name__ == "__main__":
main()