linux epoll 简单例子

         照例,只有服务端,测试用telnet.

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

#define MAX_FD_NUM 20
#define MAX_BUF_LEN 1024

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        printf("Usage:%s[port]\n",argv[0]);
        return -1;
    }

    //端口号
    int portNumber = atoi(argv[1]);

    int epfd,listenfd,connfd,nfds;
    socklen_t clilen;

    //
    struct sockaddr_in clientaddr;
    bzero(&clientaddr,sizeof(clientaddr));
    struct sockaddr_in serveraddr;
    bzero(&serveraddr,sizeof(serveraddr));

    serveraddr.sin_family = AF_INET;
    inet_pton(AF_INET,"127.0.0.1",&serveraddr.sin_addr);
    serveraddr.sin_port = htons(portNumber);

    //
    listenfd = socket(PF_INET,SOCK_STREAM,0);

    int ret = bind(listenfd,(struct sockaddr*)(&serveraddr),sizeof(serveraddr));
    if(ret < 0)
    {
        perror("bind");
        return 1;
    }

    int lret = listen(listenfd,MAX_FD_NUM-1);
    if(lret < 0)
    {
        perror("listen");
        return 1;
    }

    //关联epoll事件
    struct epoll_event ev;
    struct epoll_event events[MAX_FD_NUM];
    epfd = epoll_create(MAX_FD_NUM);
    if(epfd < 0)
    {
        perror("epoll_create");
    }

    ev.data.fd = listenfd;
    ev.events = EPOLLIN;//model LT
    epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev);

    char buf[MAX_BUF_LEN]={0};

    while(1)
    {
        nfds = epoll_wait(epfd,events,MAX_FD_NUM,-1);

        if(nfds < 0)
        {
            perror("epoll_wait");
            break;
        }

        printf("nfds:%d\n",nfds);
        for(int i=0;i


 

你可能感兴趣的:(网络)