0

我正在用epoll做一个连接测试,我发现如果我的客户端连接大约3800,epoll变得很慢,并且它每秒只接受一个连接,我在/etc/sysctl.conf中修改了一些系统参数,但是它不工作;

我的操作系统是 CentOS 7.6

#include <cstdio>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <iostream>


#define SERVER_WAIT_COUNT 10000
#define SERVER_LISTEN_BACKLOG 1000
int main()
{
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(12378);
    // inet_aton(addr, &(serverAddr.sin_addr));

    serverAddr.sin_addr.s_addr = INADDR_ANY;
    int ret = bind(sock_fd, (sockaddr*)&serverAddr, sizeof(sockaddr));

    ret = listen(sock_fd, 20);

    struct epoll_event ev, events[SERVER_WAIT_COUNT];
    ev.data.fd = sock_fd;
    ev.events = EPOLLET | EPOLLIN;

    int listenEpollFD = epoll_create(SERVER_LISTEN_BACKLOG);

    ret = epoll_ctl(listenEpollFD, EPOLL_CTL_ADD, sock_fd, &ev);
    printf("EPOLL_CLI_ADD: %d", EPOLL_CTL_ADD);
    static int clientCount = 0;
    while (true) {
        int eventCount = epoll_wait(listenEpollFD, events, SERVER_WAIT_COUNT, -1);
        if (eventCount == -1) {            
            continue;            
        }
        for (int i = 0; i < eventCount; i++) {
            if (events[i].data.fd == sock_fd) {
                struct sockaddr_in clientAddr;
                socklen_t client;
                accept(sock_fd, (sockaddr*)&clientAddr, &client);
                clientCount++;
                printf("accept a connection, current count: %d", clientCount);
                std::cout << "current count:" << clientCount << std::endl;
            }
        }
    }
    printf("hello from epollTest!\n");
    return 0;
}
4

0 回答 0