import socket
import json

def tcp_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_socket.bind(('localhost', 12345))
    print("[Server] 启动，等待客户端连接...")

    # 第一次握手：接收SYN
    data, addr = server_socket.recvfrom(1024)
    syn = json.loads(data.decode())
    if syn.get('SYN') == 1:
        print(f"[Server] 收到来自 {addr} 的SYN (seq={syn['seq']})")
        
        # 第二次握手：发送SYN-ACK
        server_seq = 5000  # 服务器初始序列号
        ack_num = syn['seq'] + 1
        syn_ack = {
            'SYN': 1,
            'ACK': 1,
            'seq': server_seq,
            'ack': ack_num
        }
        server_socket.sendto(json.dumps(syn_ack).encode(), addr)
        print(f"[Server] 发送SYN-ACK (seq={server_seq}, ack={ack_num})")

        # 第三次握手：接收ACK
        data, addr = server_socket.recvfrom(1024)
        ack = json.loads(data.decode())
        if ack.get('ACK') == 1 and ack['ack'] == server_seq + 1:
            print(f"[Server] 收到ACK (ack={ack['ack']})，连接已建立！")
        else:
            print("[Server] 连接失败")
    else:
        print("[Server] 无效的SYN报文")

    server_socket.close()

if __name__ == "__main__":
    tcp_server()