Linux IO多重化select

2911 ワード

select:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char*argv[])
{
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);

        struct sockaddr_in addrSrv;
        bzero(&addrSrv, sizeof(struct sockaddr_in));
        addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
        addrSrv.sin_family = AF_INET;
        addrSrv.sin_port = htons(6000);
        bind(sockfd, (struct sockaddr*)&addrSrv, sizeof(struct sockaddr));

        listen(sockfd, 3);

        struct sockaddr_in addrConn;
        socklen_t len = sizeof(struct sockaddr_in);

        fd_set allset, rset;
        FD_ZERO(&allset);
        FD_SET(sockfd, &allset);

        int maxfd = sockfd;

        int client[FD_SETSIZE];
        int i;
        for (i=0;i<FD_SETSIZE;i++)
                client[i] = -1;

        int maxi = -1;

        int sockConn;
        while (1)
        {
                rset = allset;
                int count = select(maxfd+1, &rset, NULL, NULL, NULL);
                if (FD_ISSET(sockfd, &rset))
                {
                        sockConn = accept(sockfd, (struct sockaddr*)&addrConn, &len);
                        for (i=0;i<FD_SETSIZE; i++)
                                if (client[i]<0)
                                {
                                        client[i] = sockConn;
                                        break;
                                }

                        if (maxi < i)
                                maxi = i;

                        FD_SET(sockConn, &allset);

                        if (maxfd < sockConn)
                                maxfd = sockConn;
                }

                for (i=0;i<=maxi;i++)
                {
                        if ((sockConn = client[i]) < -1)
                                continue;

                        if (FD_ISSET(sockConn, &rset))
                        {
                                char buf[1024] = {0};
                                int n = read(sockConn, buf, 1024);
                                if (n == 0)
                                {
                                        close(sockConn);
                                        client[i] = -1;
                                        FD_CLR(sockConn, &allset);
                                }
                                else
                                {
                                        printf("server recv:%s
", buf); write(sockConn, "server data", strlen("server data")); } } } } close(sockfd); return 0; }