当断开连接发生时,我试图“抓住”。但我实际上不明白出了什么问题。recv() 返回 0,errno 设置为 0,ioctl 返回 0。我在网上搜索了 6 个小时,但没有成功。谁能告诉我怎么了?
问候。
bool Network::setBlocking(bool blocking)
{
// sets blocking or non-blocking mode.
int flags = blocking ? 1 : 0;
return ioctl(this->sockfd, FIONBIO, &flags) ? false : true;
}
NetworkStatus Network::status()
{
// returns socket status.
struct timeval tv;
fd_set fd;
int result = 0;
tv.tv_sec = 3;
tv.tv_usec = 0;
FD_ZERO(&fd);
FD_SET(this->sockfd, &fd);
result = select(this->sockfd + 1, &fd, 0, 0, &tv);
if(result == -1)
{
return NETWORK_ERROR;
}
else if(result)
{
return NETWORK_READYREAD;
}
else
{
return NETWORK_TIMEOUT;
}
}
int Network::bytesAvailable()
{
// returns number of bytes available.
int bytes = 0;
if(ioctl(this->sockfd, FIONREAD, &bytes) < 0 || errno)
{
return -1;
}
return bytes;
}
int Network::read(char *buffer, int size)
{
// reads data from socket.
return recv(this->sockfd, buffer, size, 0);
}
...
int main(int argc, char* argv[])
{
Network net;
...
while(true)
{
switch(net.status())
{
...
case NETWORK_READYREAD:
{
int bytesAvailable = net.bytesAvailable();
char temp[bytesAvailable];
int len = net.read(temp, bytesAvailable);
printf("len: %d\nerrno: %d\nbytesAvailable: %d\n", len, errno, bytesAvailable); // len: 0, errno: 0, bytesAvailable: 0
break;
}
}
} // status
return 0;
}