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() {
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)) {
printf("accept\n");
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("close\n");
close(cfd);
fd_arr[i] = -1;
} else {
printf("receive:%s\n", buf);
write(cfd, buf, return_num);
}
}
}
}
}
}
return 1;
}