import socket
import json
import random

def tcp_client():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_addr = ('localhost', 12345)

    # 第一次握手：发送SYN
    client_seq = random.randint(1000, 5000)  # 客户端初始序列号
    syn = {'SYN': 1, 'seq': client_seq}
    client_socket.sendto(json.dumps(syn).encode(), server_addr)
    print(f"[Client] 发送SYN (seq={client_seq})")

    # 第二次握手：接收SYN-ACK
    data, addr = client_socket.recvfrom(1024)
    syn_ack = json.loads(data.decode())
    if syn_ack.get('SYN') == 1 and syn_ack.get('ACK') == 1:
        print(f"[Client] 收到SYN-ACK (seq={syn_ack['seq']}, ack={syn_ack['ack']})")
        
        # 验证确认号是否正确
        if syn_ack['ack'] == client_seq + 1:
            # 第三次握手：发送ACK
            ack = {
                'ACK': 1,
                'ack': syn_ack['seq'] + 1
            }
            client_socket.sendto(json.dumps(ack).encode(), server_addr)
            print(f"[Client] 发送ACK (ack={syn_ack['seq'] + 1})")
            print("[Client] 连接已建立！")
        else:
            print("[Client] 确认号无效")
    else:
        print("[Client] 无效的SYN-ACK报文")

    client_socket.close()

if __name__ == "__main__":
    tcp_client()