概述
select函数demo
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#define MAX_SELECT_CLIENT 4096
int select_demo() {
//建立socket
int fd = socket(AF_INET, SOCK_STREAM, 0);
//打开端口复用
int reuse_port = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &reuse_port, sizeof(int));
//绑定地址
struct sockaddr_in bind_address;
memset(&bind_address, 0, sizeof(struct sockaddr_in));
bind_address.sin_addr.s_addr = inet_addr("0.0.0.0");
bind_address.sin_family = AF_INET;
bind_address.sin_port = htons(8088);
int code = bind(fd, (struct sockaddr *) &bind_address, sizeof(struct sockaddr_in));
if (code == -1) {
perror("bind error");
close(fd);
return -1;
}
//设置监听状态
code = listen(fd, 1024);
if (code == -1) {
perror("listen error");
close(fd);
return -1;
}
//定义可读描述符集合
fd_set read_fd_set;
FD_ZERO(&read_fd_set);
FD_SET(fd, &read_fd_set);
int fd_arr[MAX_SELECT_CLIENT];
for (int i = 0; i < MAX_SELECT_CLIENT; ++i) {
fd_arr[i] = -1;
}
int max_index = -1;
int max_fd = fd;
while (1) {
FD_ZERO(&read_fd_set);
FD_SET(fd, &read_fd_set);
for (int i = 0; i <= max_index; ++i) {
if (fd_arr[i] == -1) {
continue;
}
FD_SET(fd_arr[i], &read_fd_set);
if (fd_arr[i] > max_fd) {
max_fd = fd_arr[i];
}
}
code = select(max_fd + 1, &read_fd_set, NULL, NULL, NULL);
if (code < 0) {
perror("select error");
break;
} else if (code == 0) {
continue;
} else {
//监听到变化
if (FD_ISSET(fd, &read_fd_set)) {
// accept
printf("acceptn");
int new_fd = accept(fd, NULL, NULL);
if (new_fd == -1) {
perror("accept error");
} else {
int use_index = -1;
for (int i = 0; i < MAX_SELECT_CLIENT; ++i) {
if (fd_arr[i] == -1) {
fd_arr[i] = new_fd;
use_index = i;
break;
}
}
if (use_index == -1) {
printf("客户端连接过多...n");
continue;
}
if (use_index > max_index) {
max_index = use_index;
}
}
} else {
for (int i = 0; i <= max_index; ++i) {
int cfd = fd_arr[i];
if (FD_ISSET(cfd, &read_fd_set)) {
char buf[1024] = "";
ssize_t return_num = read(cfd, buf, 1024);
if (return_num == -1) {
perror("read error");
close(cfd);
fd_arr[i] = -1;
} else if (return_num == 0) {
printf("closen");
close(cfd);
fd_arr[i] = -1;
} else {
printf("receive:%sn", buf);
write(cfd, buf, return_num);
}
}
}
}
}
}
return 1;
}
最后
以上就是跳跃面包为你收集整理的C语言实现select-数组版select函数demo的全部内容,希望文章能够帮你解决C语言实现select-数组版select函数demo所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复