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