在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
函數將立即返回,不會阻塞等待數據到達。