This code is a function for a TCP client to connect to the server




int CnnctToServerIn(struct sockaddr_in tSvrAddr, int *piCilentFd)
{
    
    
    int iFlag = 1;
    int iRet;
    int iFd = 0;
    struct linger tSoLinger;
    struct timeval tTimeVal;

    iFd = socket(AF_INET, SOCK_STREAM, 0);
    if (iFd <= 0) {
    
    
        DPRINT(DEBUG, "GB:: socket fd = %d, err! reason:%s.", iFd, strerror(errno));
        return FAILURE;
    }

    setsockopt(iFd, IPPROTO_TCP, TCP_NODELAY, (char *)&iFlag, sizeof(iFlag));

    tTimeVal.tv_sec = 2;
    tTimeVal.tv_usec = 0;
    setsockopt(iFd, SOL_SOCKET, SO_SNDTIMEO, (char *)(&tTimeVal), sizeof(tTimeVal));

    tTimeVal.tv_sec = 2;
    tTimeVal.tv_usec = 0;
    setsockopt(iFd, SOL_SOCKET, SO_RCVTIMEO, (char *)(&tTimeVal), sizeof(tTimeVal));

    tSoLinger.l_onoff = 1;
    tSoLinger.l_linger = 0;
    setsockopt(iFd, SOL_SOCKET, SO_LINGER, (char *)(&tSoLinger), sizeof(tSoLinger));

    iRet = connect(iFd, (struct sockaddr *)(&tSvrAddr), sizeof(tSvrAddr));
    if (0 == iRet) {
    
    
        *piCilentFd = iFd;
        return SUCCESS;
    }
    else {
    
    
        close(iFd);
        printf("GB:: Connect to svr inet failed. Reason:%s.\n", strerror(errno));
        return FAILURE;
    }
}






This code is a function for a TCP client to connect to the server. Here are its specific steps:

To create a socket, use the socket(AF_INET, SOCK_STREAM, 0) function.
If the creation of the socket fails, error code FAILURE is returned.
Set the socket option TCP_NODELAY and disable the Nagle algorithm by calling setsockopt(iFd, IPPROTO_TCP, TCP_NODELAY, (char *)&iFlag, sizeof(iFlag)) to improve the real-time performance of data transmission.
Set the send timeout and receive timeout by calling setsockopt(iFd, SOL_SOCKET, SO_SNDTIMEO, (char *)(&tTimeVal), sizeof(tTimeVal)) and setsockopt(iFd, SOL_SOCKET, SO_RCVTIMEO, (char *)(&tTimeVal), sizeof (tTimeVal)) to set the timeout to 2 seconds.
Set the SO_LINGER option, enable the SO_LINGER option by calling setsockopt(iFd, SOL_SOCKET, SO_LINGER, (char *)(&tSoLinger), sizeof(tSoLinger)), and set the delayed shutdown time to 0 seconds.
Use the connect function connect(iFd, (struct sockaddr *)(&tSvrAddr), sizeof(tSvrAddr)) to connect to the specified server address.
If the connection is successful (return value is 0), save the socket file descriptor in the variable pointed to by the piCilentFd pointer and return the success code SUCCESS.
If the connection fails, close the socket, print the reason for the connection failure, and then return the failure code FAILURE.
The function of this code is to establish a TCP connection on the specified server address and save the connection result in the variable pointed to by the piCilentFd pointer.

Guess you like

Origin blog.csdn.net/m0_46376834/article/details/132890079