为了实现在线用户列表定时刷新,需要及时反映用户是否在线。
我尝试过用WSAIoctl()设置SIO_KEEPALIVE_VALS,可是返回的tcp_keeplive结构体的后两个参数都是0.不知为何原因。我写的代码如下:
#include <Winsock2.h>
#include <stdio.h>
#include <winsock.h>
#include <mswsock.h>
//#include <mstcpip.h>
struct tcp_keepalive {
u_long onoff;
u_long keepalivetime;
u_long keepaliveinterval;
};
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define SIO_RCVALL_MCAST _WSAIOW(IOC_VENDOR,2)
#define SIO_RCVALL_IGMPMCAST _WSAIOW(IOC_VENDOR,3)
#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
#define SIO_ABSORB_RTRALERT _WSAIOW(IOC_VENDOR,5)
#define SIO_UCAST_IF _WSAIOW(IOC_VENDOR,6)
#define SIO_LIMIT_BROADCASTS _WSAIOW(IOC_VENDOR,7)
#define SIO_INDEX_BIND _WSAIOW(IOC_VENDOR,8)
#define SIO_INDEX_MCASTIF _WSAIOW(IOC_VENDOR,9)
#define SIO_INDEX_ADD_MCAST _WSAIOW(IOC_VENDOR,10)
#define SIO_INDEX_DEL_MCAST _WSAIOW(IOC_VENDOR,11)
//#define ECONNRESET "104" /* Connection reset by peer*/
//#define ETIMEDOUT "110" /* Connection timed out */
//#define EHOSTUNREACH "113" /* No route to host */
#define ECONNRESET WSAECONNRESET
#define EHOSTUNREACH WSAEHOSTUNREACH
#define ETIMEDOUT WSAETIMEDOUT
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
WSACleanup( );
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
int iRET;
DWORD dwError = 0L ;
struct tcp_keepalive sKA_Settings = {0}, sReturned = {0} ;
sKA_Settings.onoff = 1 ;
sKA_Settings.keepalivetime = 5500 ; // Keep Alive in 5.5 sec.
sKA_Settings.keepaliveinterval = 3000 ; // Resend if No-Reply
DWORD dwBytes = 0L ;
if ((iRET=WSAIoctl(sockConn, SIO_KEEPALIVE_VALS, &sKA_Settings,
sizeof(sKA_Settings), NULL,0, &dwBytes,NULL, NULL))== SOCKET_ERROR)
{
return;
}
printf("%d/n",iRET);
WSAIoctl(sockConn, SIO_KEEPALIVE_VALS, &sKA_Settings,
sizeof(sKA_Settings), &sReturned, sizeof(sReturned), &dwBytes,NULL, NULL);
printf("%d,%d/n",sReturned.keepalivetime,sReturned.keepaliveinterval);
}
输出值为:
0
0,0
说明返回的sReturned.keepalivetime=0,sReturned.keepaliveinterval=0.为什么会这样?
请各位前辈高人指教!