在C++中,可以使用fcntl
函数或者ioctl
函数来设置recv
函数为非阻塞模式。下面是一个简单的示例代码:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
int main() {
int sockfd;
struct sockaddr_in serverAddr;
// 创建socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
std::cerr << "Error creating socket" << std::endl;
return -1;
}
// 设置recv函数为非阻塞模式
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
// 连接服务器
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) {
std::cerr << "Error connecting to server" << std::endl;
return -1;
}
// 使用非阻塞recv函数接收数据
char buffer[1024];
int bytesReceived = recv(sockfd, buffer, sizeof(buffer), 0);
if (bytesReceived < 0) {
std::cerr << "Error receiving data" << std::endl;
} else {
std::cout << "Received " << bytesReceived << " bytes: " << buffer << std::endl;
}
close(sockfd);
return 0;
}
在上面的代码中,通过fcntl
函数将socket设置为非阻塞模式,然后调用recv
函数进行接收数据。如果没有数据可接收,recv
函数将立即返回,不会阻塞等待数据到达。