首页 > 代码库 > 如何基于udp实现tcp协议栈

如何基于udp实现tcp协议栈

http://bbs.csdn.net/topics/280046868

使用套接字完成,按照tcp的方式在一个套接字里维持一个状态机。

//定义枚举:enmu state{CLOSED,//没有连接SYN-SENT,//发送了syn,等代服务器ackACK_RECEIVE,//接到服务器ackSYNACK_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;                breakcase 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;}

 

如何基于udp实现tcp协议栈