The simplest epoll to build muduo-2 from Epoll

Source: Internet
Author: User
Tags epoll int size

Mini-muduo Version Transfer Gate
Version 0.00 Building Muduo-1 Mini-muduo Introduction from Epoll
Version 0.01 builds the muduo-2 simplest epoll from Epoll
Version 0.02 adds the first class from the Epoll build muduo-3, by the way reactor
Version 0.03 from Epoll build muduo-4 join Channel
Version 0.04 builds muduo-5 from Epoll to join Acceptor and tcpconnection
Version 0.05 builds muduo-6 from Epoll to join EventLoop and Epoll
Version 0.06 from Epoll build muduo-7 join Imuduouser
Version 0.07 from Epoll build muduo-8 join send buffer and receive buffer
Version 0.08 build Muduo-9 from Epoll add onwritecomplate callback and buffer
Version 0.09 builds muduo-10 timer timer from Epoll
Version 0.11 building muduo-11 single-threaded reactor network model from Epoll
Version 0.12 building muduo-12 multithreaded code admission from Epoll
Version 0.13 build MUDUO-13 reactor + ThreadPool molding from Epoll

Mini-muduo v 0.01, this is the first version of Mini-muduo, the entire program is a 100-line Epoll Example

The code pasted below omits the header file reference, and the complete, executable sample can be downloaded from the GitHub, using the command git checkout v0.01 can switch to this version and browse here online

#define Max_line #define MAX_EVENTS #define MAX_LISTENFD 5 int createandlisten () {int on = 1;
    int LISTENFD = socket (af_inet, sock_stream, 0);
    struct sockaddr_in servaddr; Fcntl (LISTENFD, F_SETFL, O_nonblock);
    No-block io setsockopt (LISTENFD, Sol_socket, so_reuseaddr, &on, sizeof (on));
    servaddr.sin_family = af_inet;
    SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
    
    Servaddr.sin_port = htons (11111); if ( -1 = = Bind (LISTENFD, (struct sockaddr *) &servaddr, sizeof (SERVADDR)) {cout << "bind error, ERRN 
    O: "<< errno << Endl;  } if ( -1 = Listen (LISTENFD, MAX_LISTENFD)) {cout << "Listen error, errno:" << errno << 
    Endl
return LISTENFD;
    int main (int args, char** argv) {struct epoll_event ev, events[max_events];
    int LISTENFD,CONNFD,SOCKFD;
    int readlength;
    Char Line[max_line];
    struct sockaddr_in cliaddr; socklen_t Clilen = sizeof (strucT sockaddr_in);
    int EPOLLFD = epoll_create (1);
    if (EPOLLFD < 0) cout << "Epoll_create error, Error:" << epollfd << Endl;
    LISTENFD = Createandlisten ();
    EV.DATA.FD = LISTENFD;
    Ev.events = Epollin;

    Epoll_ctl (EPOLLFD, Epoll_ctl_add, LISTENFD, &ev);
    for (;;)
        {int FDS = epoll_wait (EPOLLFD, events, max_events,-1); 
            if (FDS = = 1) {cout << "epoll_wait error, errno:" << errno << Endl;
        Break
                for (int i = 0; i < FDS i++) {if (events[i].data.fd = = LISTENFD) {
                CONNFD = Accept (LISTENFD, (sockaddr*) &cliaddr, (socklen_t*) &clilen); if (connfd > 0) {cout << "new connection from" ;< "[" << Inet_ntoa (CLIADDR.SIN_ADDR) << ":" << ntohs (Cliaddr.sin_port) ;< "]"<<" Accept Socket FD: "<< connfd << Endl; else {cout << "accept error, CONNFD:" << Conn 
                FD << "errno:" << errno << Endl; } fcntl (CONNFD, F_SETFL, O_nonblock);
                No-block io ev.data.fd = CONNFD;
                Ev.events = Epollin;  if (-1 = = Epoll_ctl (EPOLLFD, Epoll_ctl_add, CONNFD, &ev)) cout << "Epoll_ctrl error, errno:"
            << errno << Endl; else if (events[i].events & Epollin) {if (SOCKFD = EVENTS[I].DATA.FD) < 0
                    ) {cout << "Epollin sockfd < 0 error" << Endl;
                Continue
                } bzero (line, max_line); if ((readlength = Read (SOCKFD, line, Max_line)) < 0) {if (errno = = Econnreset)
                        {cout << "econnrest closed socket FD:" << events[i].data.fd << Endl;
                    Close (SOCKFD);  ' Else if (readlength = 0) {cout << ' read 0
                    Closed socket FD: "<< events[i].data.fd << Endl;
                Close (SOCKFD);
                        else {if (write (SOCKFD, line, readlength)!= readlength)
                cout << "Error:not finished one time" << Endl;
return 0; }

Program Description:

1 three functions using Epoll

int epoll_create (int size) creates a Epoll file descriptor

int epoll_ctl (int epfd, int op, int fd, struct epoll_event *event) adds the socket descriptor to/from the Epoll Listener, modifies the registration event

int epoll_wait (int epfd, struct epoll_event * events, int maxevents, int timeout) waits for events on the Epoll descriptor and obtains events

2 The basic model of Epoll programming

Pseudo code

EPOLLFD = Epoll_create (...)                    //create Epoll Descriptor LISTENFD =                          Socket (...)                              Creates the socket bind (LISTENFD ...) for port sniffing.                            Binding Listen (LISTENFD ...)  Start listening on port Epoll_ctl (EPOLLFD, Epoll_ctl_add, listenfd ...)                                         The LISTENFD is added to the Epoll descriptor to listen for (;;)                         Infinite loops {    n = epoll_wait (...) Waiting for event occurrence of Epoll descriptor     for (0 ~ N)//multiple read and write events may occur, traversing all events     {  &N Bsp                                           if (events[i].data.fd = = LISTENFD)//The socket descriptor for the event confirms a new link,         {                Instead of a read-write event for an open socket             CONNFD = Accpet (...)                      Accept new connection for CONNFD             EPOLL_CTL (...) CONNFD joins Epoll listening, like the listenfd above       &nbsp }         ELSE if (events[i].events & Epollin)//The socket of the event is not LISTENFD but CONNFD     &N Bsp   {//And there are epollin in the event set indicating that there is data to read             n = Read (                       ...) Read Data             if (n = 0)/read to 0 bytes, need to close socket     &NBS P           Close (CONNFD)//close automatically deletes connfd from Epoll listener       &NBSP ; //No need to invoke Epoll_ctl (...
        Epoll_ctl_del ...)                            else if (...) 
 Various other event handlers are processed sequentially ...   }}
3 program is very simple, although it can run, but a lot of problems, only processing read events, no input output buffer, the entire code written in a huge for loop, these in the subsequent version of the improvement.

4 83 lines of Bzero are learned from the UNP (volume P6) because three of the memset parameters are always easy to confuse.

5 41 lines and 72 rows although only the Epollin event is registered, two other events are automatically registered: Epollerr and epollhup, and man Epoll_ctl can see the instructions.

6 54 lines and 76 lines based on the socket descriptor for the event to determine how to proceed next, if the socket descriptor is LISTENFD, it is necessary to accpet new connection, otherwise the socket of the event is CONNFD, You need to determine which events occurred, subsequent calls to read or write, and this example calls only the Read

Close is called at 7 89 lines and 95 lines two, followed by a detailed explanation of why

1 Read returns-1, and the error code is econnreset.

2 Read returns 0.

8 10 lines and 70 rows The socket is set to no-blocking mode, and the socket to join Epoll is set first to No-blocking

The LISTENFD on the 9 11 line for the listening port is set to SO_REUSEADDR

cout If a chained chain call is likely to cause a thread switch, the output is split, but the current example is single-threaded, temporarily ignoring the problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.