select

select

1. 代码

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/select.h>

#define MAX_BUFFER_SIZE 1024

int main() {
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(12345);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(listen_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));

    listen(listen_fd, 5);

    fd_set master_set;
    FD_ZERO(&master_set);
    FD_SET(listen_fd, &master_set);

    int max_fd = listen_fd;

    while (true) {
        fd_set copy_set = master_set;

        int ready_fd_num = select(max_fd + 1, &copy_set, NULL, NULL, NULL);

        for (int i = 0; i <= max_fd && ready_fd_num > 0; ++i) {
            if (FD_ISSET(i, &copy_set)) {
                ready_fd_num--;

                if (i == listen_fd) {
                    struct sockaddr_in client_addr;
                    socklen_t client_addr_len = sizeof(client_addr);
                    int client_fd = accept(listen_fd, (struct sockaddr*)&client_addr, &client_addr_len);

                    FD_SET(client_fd, &master_set);
                    if (client_fd > max_fd) {
                        max_fd = client_fd;
                    }
                } else {
                    char buffer[MAX_BUFFER_SIZE];
                    int recv_len = recv(i, buffer, MAX_BUFFER_SIZE - 1, 0);
                    if (recv_len <= 0) {
                        close(i);
                        FD_CLR(i, &master_set);
                    } else {
                        buffer[recv_len] = '\0';
                        printf("Received: %s\n", buffer);
                    }
                }
            }
        }
    }

    return 0;
}