c – 设置套接字超时?

前端之家收集整理的这篇文章主要介绍了c – 设置套接字超时?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用套接字,我不知道如何设置超时?

谢谢

int sock,connected,bytes_recieved;
char send_data [128],recv_data[128];       
SOCKADDR_IN server_addr,client_addr;    
int sin_size;
int j = 0;

::socket(AF_INET,SOCK_STREAM,0);

server_addr.sin_family = AF_INET;         
server_addr.sin_port = htons(4000);     
server_addr.sin_addr.s_addr = INADDR_ANY; 

::bind(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr));
::listen(sock,5);
::fflush(stdout);

while(1)
{  
    sin_size = sizeof(struct sockaddr_in);
    connected = ::accept(sock,(struct sockaddr *)&client_addr,&sin_size);

    while (1)
    {
        j++;

        ::send(connected,send_data,strlen(send_data),0);  

        //dealing with lost communication ? 
        //and reastablishing communication
        //set timeout and reset on timeout error    
    }
}
::closesocket(sock);

解决方法

套接字默认处于阻塞模式.如果使用ioctlsocket(FIONBIO)将其切换到非阻塞模式,则可以使用select()来管理超时:
SOCKET sock,connected;
int bytes_recieved;  
char send_data [128],recv_data[128];         
SOCKADDR_IN server_addr,client_addr;      
int sin_size;  
int j = 0,ret;  
fd_set fd;
timeval tv;

sock = ::socket(AF_INET,0);  

server_addr.sin_family = AF_INET;           
server_addr.sin_port = htons(4000);       
server_addr.sin_addr.s_addr = INADDR_ANY;   

::bind(sock,sizeof(struct sockaddr));  
::listen(sock,1);  
::fflush(stdout);  

u_long nbio = 1;
::ioctlsocket(sock,FIONBIO,&nbio);

while(1) 
{   
    FD_ZERO(&fd);
    FD_SET(sock,&fd);

    tv.tv_sec = 5;
    tv.tv_usec = 0;

    if (select(0,&fd,NULL,&tv) > 0)
    {
        sin_size = sizeof(struct sockaddr_in); 
        connected = ::accept(sock,&sin_size); 

        nbio = 1;
        ::ioctlsocket(connected,&nbio);

        while (1) 
        { 
            j++; 

            if (::send(connected,0) < 0)
            {
                //dealing with lost communication ?  
                //and reastablishing communication 
                //set timeout and reset on timeout error     

                if (WSAGetLastError() == WSAEWOULDBLOCK)
                {
                    FD_ZERO(&fd);
                    FD_SET(connected,&fd);

                    tv.tv_sec = 5;
                    tv.tv_usec = 0;

                    if (select(0,&tv) > 0)
                        continue;
                }

                break;
            }
        } 

        closesocket(connected);
    } 
}
原文链接:https://www.f2er.com/c/112797.html

猜你在找的C&C++相关文章