socket 设备自动重启/断电 recv send阻塞的解决办法

 socket 设备自动重启/断电 recv send阻塞的解决办法
 
 (1)使用socket的KeepAlive机制,当突然断电后,recv函数阻塞超时退出,不会造成程序死锁,或者程序一直阻塞在recv函数的问题,方法如下:

 

//
 BOOL bKeepAlive = TRUE;
 nRet=setsockopt(listen_sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&bKeepAlive, sizeof(bKeepAlive));

 if (nRet==SOCKET_ERROR) 
 { 
  printf("setsockopt failed : %d\n", WSAGetLastError()); 
  return FALSE; 
 } 

 struct tcp_keepalive alive_in;
 struct tcp_keepalive alive_out;
 alive_in.keepalivetime  = 5000;
 alive_in.keepaliveinterval = 2000;
 alive_in.onoff   = TRUE;
 unsigned long ulBytesReturn = 0;

 nRet=WSAIoctl(listen_sock, SIO_KEEPALIVE_VALS, &alive_in, sizeof(alive_in), &alive_out, sizeof(alive_out),
  &ulBytesReturn, NULL, NULL);

 if (nRet == SOCKET_ERROR) 
 { 
  printf("setsockopt failed : %d\n", WSAGetLastError()); 
  return FALSE; 
 } 
 
 //

 

同时判断设备是否掉线的方法有2个,一个为心跳包,一个还是KeepAlive 机制

你可能感兴趣的:(socket 设备自动重启/断电 recv send阻塞的解决办法)