select监听多个client -- linux函数

使用select函数能够以非堵塞的方式和多个socket通信。程序仅仅是演示select函数的使用,功能很easy,即使某个连接关闭以后也不会改动当前连接数。连接数达到最大值后会终止程序。

1. 程序使用了一个数组fd_A,通信開始后把须要通信的多个socket描写叙述符都放入此数组。


2. 首先生成一个叫sock_fd的socket描写叙述符,用于监听port。

3. 将sock_fd和数组fd_A中不为0的描写叙述符放入select将检查的集合fdsr。

4. 处理fdsr中能够接收数据的连接。假设是sock_fd,表明有新连接增加。将新增加连接的socket描写叙述符放置到fd_A。

这部分代码实现逻辑不错,只是有点bug,对套接字缓存未做处理完整。

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

#define MYPORT 1234    // the port users will be connecting to
#define BACKLOG 5     // how many pending connections queue will hold
#define BUF_SIZE 200
int fd_A[BACKLOG];    // accepted connection fd
int conn_amount;    // current connection amount

void showclient()
{
    int i;
    printf("client amount: %d
", conn_amount);

    for (i = 0; i < BACKLOG; i++) {

        printf("[%d]:%d  ", i, fd_A[i]);

    }
    printf("

");
}

int main(void)
{
    int sock_fd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct sockaddr_in server_addr;    // server address information
    struct sockaddr_in client_addr; // connector's address information
    socklen_t sin_size;
    int yes = 1;
    char buf[BUF_SIZE];
    int ret;
    int i;

    if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
        perror("setsockopt");
        exit(1);
    }
   
    server_addr.sin_family = AF_INET;         // host byte order
    server_addr.sin_port = htons(MYPORT);     // short, network byte order
    server_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
    memset(server_addr.sin_zero, '