SO_RCVTIMEOC语言使用示例
时间: 2024-11-08 08:12:13 浏览: 7
SO_RCVTIMEO是Berkeley Socket API中用于设置接收超时的一个标志,它在recv()函数中使用。当这个标志设置并且等待接收数据的时间超过设定的值时,recv()会返回0,并设置errno为EAGAIN(资源暂时不可用)或EWOULDBLOCK(请求立即阻塞)。这是一个非阻塞I/O的例子:
```c
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int socket_desc = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080); // 设置服务器端口号
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
// 将SO_RCVTIMEO设置为1秒超时
struct timeval timeout;
timeout.tv_sec = 1; // 超时时间(秒)
timeout.tv_usec = 0; // 微秒部分(对于秒级别,通常是0)
setsockopt(socket_desc, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout, sizeof(timeout));
// 非阻塞模式下尝试连接
fcntl(socket_desc, F_SETFL, O_NONBLOCK);
ssize_t bytes_received = recv(socket_desc, buffer, BUF_SIZE, MSG_DONTWAIT); // MSG_DONTWAIT标志表示立即返回
if (bytes_received > 0) {
printf("Received %zd bytes of data.\n", bytes_received);
} else if (bytes_received == 0) { // 空闲连接,对方已关闭
printf("Connection closed by peer.\n");
} else if (errno == EAGAIN || errno == EWOULDBLOCK) { // 超时或无数据可读
printf("No data available yet or timeout occurred.\n");
} else {
perror("Error receiving data");
}
close(socket_desc);
return 0;
}
阅读全文