#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;
}