http://bbs.csdn.net/topics/280046868
使用套接字完成,按照tcp的方式在一个套接字里维持一个状态机。
//定义枚举: enmu state{ CLOSED,//没有连接 SYN-SENT,//发送了syn,等代服务器ack ACK_RECEIVE,//接到服务器ack SYNACK_SEND,//恢复服务器的ack,确认 ESTABLISHED,//成功建立 } //定义你自己的用udp连接函数 int newconnect( int sd, const struct sockaddr * sa, int namelen ) { int err = -1; int state = CLOSED; char ** buff[128] = {"syn","synack"}; char buffrom[128]; memset(buff,0,128); while(true)//开始状态机转换 { if( state == ESTABLISHED ) break; switch(state) { case CLOSED: err = sendto( sd, buff[0], strlen(buff[0]), 0, sa, namelen ); if( err == SOCKET_ERROR ) goto error; state = SYN-SENT; break; case SYN-SENT: err = recvfrom( sd, buffrom, strlen(buffrom), sa, namelen ); if( err == SOCKET_ERROR ) goto error; if( !strcmp(buffom,"ack",3) ) state = ACK_RECEIVE; break; case ACK_RECEIVE: err = sendto( sd, buff[1], strlen(buff[1]), 0, sa, namelen ); if( err == SOCKET_ERROR ) goto error; state = ESTABLISHED: break; case ESTABLISHED: break; default: break; } } return sd; err: closesocket(sd); return NULL; }
时间: 2024-12-29 16:10:18