epoll实现IO多路复用服务器代码

epoll 服务器端:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define BUFLEN 128
int main(int argc, char const *argv[])
{
    int serverFd, clientFd;
    int len, ret, rlen;
    char buf[BUFLEN];
    struct sockaddr_in serverAddr, clientAddr;
    if (argc != 2)
    {
        printf("usage: %s port\n", argv[0]);
        return 0;
    }
    short port = atoi(argv[1]);
    len = sizeof(serverAddr);

    serverFd = socket(AF_INET, SOCK_STREAM, 0);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(port);
    serverAddr.sin_addr.s_addr = 0;
    int reuse = 1;
    setsockopt(serverFd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int));
    ret = bind(serverFd, (struct sockaddr *)&serverAddr, len);
    if (ret < 0)
    {
        perror("bind failed");
        return -1;
    }
    ret = listen(serverFd, 10);
    if (ret < 0)
    {
        perror("listen failed");
        return -1;
    }

    int epfd, epct, i;
    struct epoll_event event;      //定义epoll事件
    struct epoll_event events[20]; //定义epooll事件集合
    memset(events, 0, 20 * sizeof(struct epoll_event));
    epfd = epoll_create(1); //创建epoll的fd
    event.data.fd = serverFd;
    event.events = EPOLLIN;
    epoll_ctl(epfd, EPOLL_CTL_ADD, serverFd, &event); //把serverFd添加到监听
    while (1)
    {
        epct = epoll_wait(epfd, events, 20, -1);
        for (i = 0; i < epct; i++)
        {
            if (events[i].data.fd == serverFd)
            {
                clientFd = accept(events[i].data.fd, (struct sockaddr *)&clientAddr, &len);
                printf("newfd=%d ip=%s\n", clientFd, inet_ntoa(clientAddr.sin_addr));

                event.data.fd = clientFd;
                // event.events = EPOLLIN;
                event.events = EPOLLIN | EPOLLET;
                epoll_ctl(epfd, EPOLL_CTL_ADD, clientFd, &event);
            }
            else
            {
                memset(buf, 0, BUFLEN);
                rlen = read(events[i].data.fd, buf, BUFLEN);
                if (rlen == 0)
                {
                    printf("fd %d disconnected\n", events[i].data.fd);
                    close(events[i].data.fd);
                    epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, &event);
                    continue;
                }
                printf("fd:%d data=%s\n", events[i].data.fd, buf);
            }
        }
    }

    return 0;
}

你可能感兴趣的:(服务器,运维)