C++ Socket programming send rev blocking set blocking timeout

int nTimeout,=1000;

set

//Set the send timeout to 1000ms
if( SOCKET_ERROR == setsockopt( sockClient, SOL_SOCKET, SO_SNDTIMEO,
                               (char *)&nTimeout, sizeof( int ) ) )
{
fprintf( stderr, "Set SO_SNDTIMEO error !\n" );
}
//Set the receive timeout to 1000ms
if( SOCKET_ERROR == setsockopt( sockClient, SOL_SOCKET, SO_RCVTIMEO,
                               (char *)&nTimeout, sizeof( int ) ) )
{
fprintf( stderr, "Set SO_RCVTIMEO error !\n" );
}


Notice:

1. The fourth parameter of rev() needs to be set to MSG_WAITALL, which will block all the time until the specified number of data arrives before returning unless the timeout period arrives. If the receive timeout is set, it is also valid without MSG_WAITALL,

2. Even if the waiting timeout value has not expired, the other party closes the socket(). rev() will immediately return the received data byte.


#include <WINSOCK2.H>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
int main(int argc,char **argv)
{
    // Create socket 
    WORD myVersionRequest;
    WSADATA wsaData;
    myVersionRequest=MAKEWORD(1,1);
    int err;
    err=WSAStartup(myVersionRequest,&wsaData);
    if (!err){
        printf( " Socket opened\n " );
    }else{
        printf( " ERROR: Nested word not open! " );
         return  1 ;
    }
    // Further bind the socket 
    SOCKET serSocket=socket(AF_INET,SOCK_STREAM, 0 ); // Create an identifiable socket

    // The parameters that need to be bound 
    SOCKADDR_IN addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.S_un.S_addr =htonl(INADDR_ANY); // ip address 
    addr.sin_port=htons( 6000 ); // binding port 

    bind(serSocket,(SOCKADDR *)&addr, sizeof (SOCKADDR)); // binding Determined to complete 
    listen(serSocket, 5 ); // The second parameter represents the maximum number of connections that can be received

    ///////////////////////////////////////////// ///////////////////// // 
    // Start listening 
    ///////////////////// ///////////////////////////////////////////// // 
    SOCKADDR_IN clientsocket;
     int len = sizeof (SOCKADDR);
     while ( 1 )
    {
        SOCKET serConn =accept(serSocket,(SOCKADDR*)&clientsocket,&len); // If this is not accept but consideration. . It will constantly monitor 
        char sendBuf[ 100 ];

        sprintf(sendBuf, " hello, %s ! " ,inet_ntoa(clientsocket.sin_addr)); // Find the corresponding IP and print this line there 
        printf( " Send:%s\n " ,sendBuf);
        send(serConn,sendBuf,strlen(sendBuf)+1,0);

        char receiveBuf[100];//接收
        recv(serConn,receiveBuf,sizeof(receiveBuf),0);
        printf("recv:%s\n",receiveBuf);

        closesocket(serConn); // Close 
        WSACleanup(); // Release resources 
        return  0 ;
    }
    return 1;
}

Client 

bool CTcpSocket::Connect()
{
// SOCKET sockClient = socket (AF_INET, SOCK_STREAM, 0);
sockClient = socket (AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrSrv;
//addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_addr.S_un.S_addr   = inet_addr(m_server.c_str());
addrSrv.sin_family   = AF_INET;
addrSrv.sin_port   = htons( m_port );


int nTimeout = TCP_TIME_MAX;
//Set the send timeout to 1000ms
if( SOCKET_ERROR == setsockopt( sockClient, SOL_SOCKET, SO_SNDTIMEO,
                               (char *)&nTimeout, sizeof( int ) ) )
{
fprintf( stderr, "Set SO_SNDTIMEO error !\n" );
}
//Set the receive timeout to 1000ms
if( SOCKET_ERROR == setsockopt( sockClient, SOL_SOCKET, SO_RCVTIMEO,
                               (char *)&nTimeout, sizeof( int ) ) )
{
fprintf( stderr, "Set SO_RCVTIMEO error !\n" );
}


if( connect( sockClient, (SOCKADDR*)&addrSrv, sizeof( SOCKADDR ) ) == 0 )
{
 // CLOG::Out0( L"DEBUG", L"%d.client connect:%s,%d" ,sockClient,CComon::ToCString( inet_ntoa(addrSrv.sin_addr)),ntohs(addrSrv.sin_port));  
return true;
} else
{
return false;
}


//true;
}


接收开辟一个线程

 /**
 * @brief  Receive datas from severs.
 * @note
 * @param
 * @retval None
 */
int CTcpSocket::Receive( __out_bcount_part(len, return ) __out_data_source(NETWORK) char FAR * buf,
                            __in int len )
{
int re = recv( sockClient, buf, len, 0 );
return re;
}

/**
 * @brief  Receive datas from severs.
 * @note
 * @param
 * @retval None
 */
UINT SocketReceivePross(void *pagram)
{
    CTcpSocket *temp=  (CTcpSocket*) pagram;
while (1)
{
memset(temp->dataBuf,0,BUF_SZIE);
  int length= temp->Receive(temp->dataBuf, sizeof(temp->dataBuf)); //阻塞等待5S
if ( length>0)
{
temp->Analysis();
}
  ::Sleep(1); 
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325516940&siteId=291194637