socket 阻塞accept()read()C语言
时间: 2024-11-16 17:20:44 浏览: 28
在C语言中,`accept()` 函数通常与 `select()` 或 `poll()` 等多路复用IO机制一起使用以实现阻塞式等待客户端连接。`accept()` 是在服务器端执行的,它会阻塞直到有新的连接请求到来。一旦连接请求到达,它会创建一个新的套接字描述符来代表客户端连接,并返回这个描述符。
以下是简单的示例:
```c
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/select.h>
int main() {
// ... 建立监听套接字 ...
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
// 设置超时时间(这里设为1秒)
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
while (true) {
// 使用select()等待可读事件
if (select(sockfd + 1, &readfds, NULL, NULL, &timeout) == -1) {
perror("Error in select");
break;
}
// 如果套接字准备好接受连接
if (FD_ISSET(sockfd, &readfds)) {
int client_sockfd = accept(sockfd, NULL, NULL);
if (client_sockfd == -1) {
perror("Error accepting connection");
} else {
printf("Accepted connection from client.\n");
// 这里可以开始处理客户端的数据
}
}
}
return 0;
}
```
在这个示例中,`select()` 被用来监控套接字描述符集合是否有可读事件发生。如果`accept()` 返回一个新的套接字描述符,说明客户端已经连接,然后你可以继续进行数据交互。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)