有两种可能性:发生错误或将套接字设置为非阻塞模式。要查看是否发生错误时,检查recv
返回值:
while() {
char buf[1024];
int ret = recv(,buf,,)
if(ret < 0) {
// handle error
printf("recv error: %s\n", strerror(errno));
} else {
// only use the first ret bytes of buf
processMsg(buf, ret);
}
}
为了把插座成非阻塞模式,或者查询如果套接字是非阻塞模式,使用fcntl(2)
与O_NONBLOCK
标志:
// Test if the socket is in non-blocking mode:
if(fcntl(sockfd, F_GETFL) & O_NONBLOCK) {
// socket is non-blocking
}
// Put the socket in non-blocking mode:
if(fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL) | O_NONBLOCK) < 0) {
// handle error
}
需要注意的是,除非你明确地改变了阻塞行为,插座应被默认阻止,所以最有可能发生错误时。
您最好检查'recv'的返回码。当你高兴地看着缓冲区中的一些垃圾时,它可以尖叫一个错误... – 2011-06-13 02:14:51
你还需要考虑接收部分消息或更多字节的可能性,而不是一个消息的价值。如果发送者发送500字节的消息,则您的RECV呼叫可能只能检索200个字节,或者可能检索700个字节(如果您的发送者可以在不等待响应的情况下发送多条消息)。 – 2011-06-13 03:28:33
在我之前的评论中应该包含一个指向[此TCP碎片讨论](http://stackoverflow.com/questions/4552855/tcp-fragmentation)的链接。 – 2011-06-13 03:35:03