epoll完整例子

#include <sys/socket.h>
 
 
  
  
   
   
    
    
     
     
      
       
        
         
        
      
     
     
    
    
   
   
  
  
 
 

#include <sys/epoll.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <fcntl.h>

#include <unistd.h>

#include <stdio.h>

#include <errno.h>

#define MAXLINE 100

void
setnonblocking (int sock)
{
  int opts = 0;
  opts = fcntl (sock, F_GETFL);
  if (opts < 0)
  {
  perror ("fcntl get failed!");
  return;
  }
  opts = opts | O_NONBLOCK;
  if (fcntl (sock, F_SETFL, opts) < 0)
  {
  perror ("fcntl set failed!");
  return;
  }
}

int
main ()
{
  int i, maxi, listenfd, connfd, sockfd, epfd, nfds;
  size_t n;
  char line[1024];
  socklen_t clilen;
  struct epoll_event ev, events[20];
  epfd = epoll_create (256);
  struct sockaddr_in clientaddr;
  struct sockaddr_in serveraddr;
  listenfd = socket (AF_INET, SOCK_STREAM, 0);
  setnonblocking (listenfd);

  ev.data.fd = listenfd;
  ev.events = EPOLLIN | EPOLLET;
  epoll_ctl (epfd, EPOLL_CTL_ADD, listenfd, &ev);

  serveraddr.sin_family = AF_INET;
  serveraddr.sin_port = htons (8888);
  inet_aton ("202.117.10.184", &(serveraddr.sin_addr));
  bind (listenfd, (struct sockaddr *) &serveraddr, sizeof (serveraddr));
  listen (listenfd, 20);
  maxi = 0;
  for (;;)
  {
  nfds = epoll_wait (epfd, events, 20, -1);
  for (i = 0; i < nfds; i++)
 {
  if (events[i].data.fd == listenfd)
  {
  clilen = sizeof (clientaddr);
  connfd =
  accept (listenfd, (struct sockaddr *) &clientaddr, &clilen);
  if (connfd < 0)
  {
  perror ("connfd < 0");
  return 1;
  }
  setnonblocking (connfd);
  fprintf (stdout, "connect form: %s/n",
  inet_ntoa (clientaddr.sin_addr));
  ev.data.fd = connfd;
  ev.events = EPOLLIN | EPOLLET;
  epoll_ctl (epfd, EPOLL_CTL_ADD, connfd, &ev);
  }
  else if (events[i].events & EPOLLIN)
  {
  if ((sockfd = events[i].data.fd) < 0)
  continue;
  if ((n = read (sockfd, line, sizeof (line))) < 0)
  {
  if (ECONNRESET == errno)
  {
  close (sockfd);
  events[i].data.fd = -1;
  }
  else
  {
  fprintf (stderr, "readerror!");
  }
  }
  else if (0 == n)
  {
  close (sockfd);
  events[i].data.fd = -1;
  }
  else
  {
  line[n] = '/0';
  fprintf (stdout, "read: %s/n", line);
  }
  ev.data.fd = sockfd;
  ev.events = EPOLLOUT | EPOLLET;
  epoll_ctl (epfd, EPOLL_CTL_MOD, sockfd, &ev);
  }
  else if (events[i].events & EPOLLOUT)
  {
  n = strlen (line);
  sockfd = events[i].data.fd;
  write (sockfd, line, n);
  ev.data.fd = sockfd;
  ev.events = EPOLLIN | EPOLLET;
  epoll_ctl (epfd, EPOLL_CTL_MOD, sockfd, &ev);
  }
 }
  }
  return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值