目錄

L05-sockets.py

labs/L05-sockets.pyPython · 75 行下載原始檔

用於 L05 本機 TCP 與 UDP 訊息

#!/usr/bin/env python3
"""Real loopback TCP framing and UDP datagrams, Python standard library only."""
import argparse
import json
import socket
import struct
from concurrent.futures import ThreadPoolExecutor

LONG=b'x'*100  # Fourth TCP message, sent only with --truncate.


def read_exact(sock,count,allow_clean_eof=False):
    chunks=[];remaining=count
    while remaining:
        part=sock.recv(min(remaining,2))  # Force small API reads; not a claim about TCP segment size.
        if not part:
            if allow_clean_eof and remaining==count:return None
            raise EOFError(f'EOF with {remaining} bytes missing')
        chunks.append(part);remaining-=len(part)
    return b''.join(chunks)


def receive_message(sock):
    header=read_exact(sock,4,allow_clean_eof=True)
    if header is None:return None
    size=struct.unpack('!I',header)[0]
    if size>4096:raise ValueError('message exceeds lab limit')
    return read_exact(sock,size)


def demo(truncate=None):
    """truncate=N appends LONG but sends only its first N payload bytes, then closes the write side."""
    if truncate is not None and not 0<=truncate<len(LONG):raise ValueError(f'truncate must be 0 to {len(LONG)-1}')
    messages=[b'cat','網路'.encode('utf-8'),b'']
    with socket.socket() as server,ThreadPoolExecutor(max_workers=1) as pool:
        server.bind(('127.0.0.1',0));server.listen();server.settimeout(5)
        def serve():
            with server.accept()[0] as conn:
                conn.settimeout(5)
                result=[]
                while True:
                    try:message=receive_message(conn)
                    except EOFError as error:
                        if truncate is None:raise
                        return result,f'EOFError: {error}'  # Parser refuses the partial message.
                    if message is None:return result,None
                    result.append(message.decode('utf-8'))
        future=pool.submit(serve)
        with socket.create_connection(server.getsockname(),timeout=5) as client:
            wire=b''.join(struct.pack('!I',len(m))+m for m in messages)
            if truncate is not None:wire+=struct.pack('!I',len(LONG))+LONG[:truncate]
            client.sendall(wire);client.shutdown(socket.SHUT_WR)
        tcp,error=future.result(timeout=6)
    with socket.socket(type=socket.SOCK_DGRAM) as receiver,socket.socket(type=socket.SOCK_DGRAM) as sender:
        receiver.bind(('127.0.0.1',0));receiver.settimeout(5)
        for message in messages[:2]:sender.sendto(message,receiver.getsockname())
        udp=[receiver.recvfrom(4096)[0].decode('utf-8') for _ in range(2)]
    out={'kind':'real loopback sockets','tcp_messages':tcp}
    if truncate is not None:
        out.update(tcp_error=error,truncated_message={'declared_bytes':len(LONG),'sent_payload_bytes':truncate})
    out.update(udp_datagrams=udp,
               note='recv chunks are limited by application; TCP segment sizes are not measured; UDP loopback demonstration assumes no loss/reordering.')
    return out


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--truncate',type=int,metavar='N',
                        help='append a 100-byte TCP message, send only its first N payload bytes (0-99), then close the write side')
    args=parser.parse_args()
    if args.truncate is not None and not 0<=args.truncate<len(LONG):parser.error(f'--truncate must be 0 to {len(LONG)-1}')
    print(json.dumps(demo(args.truncate),ensure_ascii=False,indent=2))


if __name__=='__main__':main()