select監聽多個client -- linux函式

weixin_30588675發表於2020-04-05

使用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\n", conn_amount);

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

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

    }
    printf("\n\n");
}

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, '\0', sizeof(server_addr.sin_zero));

    if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind");
        exit(1);
    }

    if (listen(sock_fd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }
    printf("listen port %d\n", MYPORT);
    fd_set fdsr;
    int maxsock;
    struct timeval tv;
    conn_amount = 0;

    sin_size = sizeof(client_addr);
    maxsock = sock_fd;
    while (1) {
        // initialize file descriptor set
        FD_ZERO(&fdsr);
        FD_SET(sock_fd, &fdsr);
        // timeout setting
        tv.tv_sec = 30;
        tv.tv_usec = 0;
        // add active connection to fd set

        for (i = 0; i < BACKLOG; i++) {
            if (fd_A[i] != 0) {
                FD_SET(fd_A[i], &fdsr);
            }
        }

        ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);
        if (ret < 0) {
            perror("select");
            break;
        } else if (ret == 0) {
            printf("timeout\n");
            continue;
        }

        // check every fd in the set
        for (i = 0; i < conn_amount; i++) {
            if (FD_ISSET(fd_A[i], &fdsr)) {
                ret = recv(fd_A[i], buf, sizeof(buf), 0);
                if (ret <= 0) {        // client close
                    printf("client[%d] close\n", i);
                    close(fd_A[i]);
                    FD_CLR(fd_A[i], &fdsr);
                    fd_A[i] = 0;
                } else {        // receive data
                    if (ret < BUF_SIZE)
                        memset(&buf[ret], '\0', 1);
                    printf("client[%d] send:%s\n", i, buf);
                }
            }
        }

        // check whether a new connection comes
        if (FD_ISSET(sock_fd, &fdsr)) {
            new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);
            if (new_fd <= 0) {
                perror("accept");
                continue;
            }

            // add to fd queue
            if (conn_amount < BACKLOG) {
                fd_A[conn_amount++] = new_fd;
                printf("new connection client[%d] %s:%d\n", conn_amount,
                        inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                if (new_fd > maxsock)
                    maxsock = new_fd;
            }
            else {
                printf("max connections arrive, exit\n");
                send(new_fd, "bye", 4, 0);
                close(new_fd);
                break;
            }
        }
        showclient();
    }

    // close other connections
    for (i = 0; i < BACKLOG; i++) {
        if (fd_A[i] != 0) {
            close(fd_A[i]);
        }
    }

    exit(0);

}


我這裡做改動(大概邏輯)

    for(i=0;i<BACKLOG;i++)
    {
        tcpSockIndex[i] = -1;
    }
    
	while(1)
	{
		FD_ZERO(&readfds);
		FD_SET(tcpSock, &readfds);
        
        maxfdp = maxfdp>tcpSock?maxfdp:tcpSock;
        
        for(i=0;i<BACKLOG;i++)
        {
//            AB_LOG("FD_SET tcpSockIndex[%d] = %d.\n", i, tcpSockIndex[i]);
            if(-1 != tcpSockIndex[i])
            {
                FD_SET(tcpSockIndex[i], &readfds);
                maxfdp = maxfdp>tcpSockIndex[i]?

maxfdp:tcpSockIndex[i]; } } timeout.tv_sec = SELECT_TIME_OUT_TM; timeout.tv_usec = 0; ret = select(maxfdp+1, &readfds, NULL, NULL, &timeout); if(ret < 0) { AB_PERROR("select error!\n"); return ; } else if(0 == ret) { AB_PERROR("select time out!\n"); } //處理client傳送的報文 for(i=0; i<BACKLOG; i++) { if ( -1 != tcpSockIndex[i] && FD_ISSET(tcpSockIndex[i], &readfds)) { AB_LOG("--- tcp client ---.\n"); pthread_t pthd2; TCP_SOCK_T * pTcpSock = NULL; pTcpSock = (TCP_SOCK_T *)malloc(sizeof(TCP_SOCK_T)); pTcpSock->sock = tcpSockIndex[i]; pthread_create(&pthd2, NULL, bc_sock_handle_client_data, (void *)pTcpSock); #if 0 bc_sock_handle_client_data(tcpSockIndex[i]); ret = read(tcpSockIndex[i], NULL, 0); AB_LOG("close tcpSockIndex[%d] = %d, ret = %d.\n", i, tcpSockIndex[i], ret ); //關閉client連線的套接字 if(-1 == tcpSockIndex[i]) close(tcpSockIndex[i]); #endif //清空client字符集 FD_CLR(tcpSockIndex[i], &readfds); tcpSockIndex[i] = -1; tcpClientConnNum --; } } //獲取client連線過來的套接字 if(FD_ISSET(tcpSock, &readfds)) { AB_LOG("--- tcp server ---.\n"); if((tcpSockClient = accept(tcpSock, (struct sockaddr*)&chiAddr, &cliLen)) <= 0 ) { AB_PERROR("BCHV accept socket error: %s(errno: %d).\n",strerror(errno), errno); continue; } //在套接字陣列中找出一個可用加入的位置。

for(i=0,tcpSockFlag=0; i<BACKLOG; i++) { AB_LOG("tcpSockIndex[%d] = %d.\n", i, tcpSockIndex[i]); if(-1 == tcpSockIndex[i]) { tcpSockIndex[i] = tcpSockClient; tcpClientConnNum ++; AB_LOG("new connection client[%d] %08X:%d.\n", tcpClientConnNum, chiAddr.sin_addr.s_addr, ntohs(chiAddr.sin_port)); //錯誤列印 //AB_LOG("new connection client[%d] %s.\n", tcpClientConnNum, // inet_ntoa(chiAddr.sin_addr)); #if 0 if (sock_c > maxfdp) maxfdp = sock_c; #endif tcpSockFlag = 1; break; } } //超過最大連線請求。能夠傳送client斷開連線 if(0 == tcpSockFlag) { AB_LOG("max connections arrive, exit\n"); send(tcpSockClient, "bye", 4, 0); close(tcpSockClient); } } } //關閉全部client套接字 for(i=0; i<BACKLOG; i++) { if(-1 != tcpSockIndex[i]) { close(tcpSockIndex[i]); } }



文章摘自 http://www.cnblogs.com/faraway/archive/2009/03/06/1404449.html

轉載於:https://www.cnblogs.com/jzssuanfa/p/7258914.html

相關文章