问题描述
我的server程序:listen:structsockaddr_inr_myaddr;wVersionRequested=MAKEWORD(2,2);rc=WSAStartup(wVersionRequested,&wsdata);/*createsocket*/fd_socket=WSASocket(PF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED);/*bindsockettomyownIPaddress*/r_myaddr.sin_addr.s_addr=inet_addr(s_localhost_ip);r_myaddr.sin_port=htons(0);r_myaddr.sin_family=AF_INET;bind(fd_socket,(structsockaddr*)&r_myaddr,sizeof(r_myaddr))/*listenatsocketforconnection*/if(listen(fd_socket,LISTEN_BACKLOG)==SOCKET_ERROR){}return(fd_socket);ACCEPT:fd_socket_accept=accept(fd_socket_listening,(structsockaddr*)&r_peeraddr,&i_addrlen);RECV:i_retcd=setsockopt(fd_socket,SOL_SOCKET,SO_RCVTIMEO,(char*)&i_timeout,sizeof(i_timeout));recv(fd_socket,ps_buf,l_len,0);...这样的写法正常,可以处理超时.但其对应的client端就不行了,connect函数:wVersionRequested=MAKEWORD(2,2);rc=WSAStartup(wVersionRequested,&wsdata);r_peeraddr.sin_family=AF_INET;r_peeraddr.sin_addr.s_addr=inet_addr(s_peer_ip);r_peeraddr.sin_port=htons(t_peer_port);/*createsocket*/fd_socket=WSASocket(PF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED);/*bindsockettomyownIPaddress*/r_myaddr.sin_addr.s_addr=inet_addr(s_localhost_ip);r_myaddr.sin_port=htons(0);r_myaddr.sin_family=AF_INET;bind(fd_socket,(structsockaddr*)&r_myaddr,sizeof(r_myaddr))i_outcome=connect(fd_socket,(structsockaddr*)&r_peeraddr,sizeof(structsockaddr_in));RECV:i_retcd=setsockopt(fd_socket,SOL_SOCKET,SO_RCVTIMEO,(char*)&i_timeout,sizeof(i_timeout));recv(fd_socket,ps_buf,l_len,0);...这时,编译,运行都没有问题,但是超时很严重,根本出不来也就是说,setsockopt(fd_socket,SOL_SOCKET,SO_RCVTIMEO,(char*)&i_timeout,sizeof(i_timeout));对server有效,但对client无效,请高手帮忙看是哪里出问题了,非常感谢!
解决方案
解决方案二:
解决:函数如下:longarch_tcp_recv(SOCKETfd_socket,chars_buf[],longl_msgsize,longl_timeout){char*ps_buf;longl_read_so_far=0L;longl_read=0L;longl_len;longl_alarm_wait=0L;DWORDStart;DWORDEnd;inti_retcd;l_timeout=l_timeout*1000;i_retcd=setsockopt(fd_socket,SOL_SOCKET,SO_RCVTIMEO,(char*)&l_timeout,sizeof(l_timeout));if(i_retcd!=0){/*报错:setsockoptSO_RCVTIMEOfailed*/return(-1);}Start=GetTickCount();while(l_read_so_far<l_msgsize){ps_buf=s_buf+l_read_so_far;l_len=l_msgsize-l_read_so_far;l_read=recv(fd_socket,ps_buf,l_len,0);if(l_read==SOCKET_ERROR){/*报错:recvfromsocket(%d)failed:retcd=%d",fd_socket,l_read*/return(-1);}if(l_read>0){l_read_so_far+=l_read;}if(l_read==0){/*报错:recvfromsocket(%d)failed:theconnectionhasbeengracefullyclosed.",fd_socket*/return(-1);}End=GetTickCount();if(End-Start>(DWORD)l_timeout){/*报错:timeout(%d):elapse(%d)",l_timeout,End-Start*/return(-1);}}return(l_read_so_far);}/*arch_tcp_recv*/