Varuna Jayasiri

Programmer

Page 3


TCP Echo Server Example in C++ Using Epoll

This example is a simple server which accepts connections and echos whatever data sent to the server. This example also demonstrates the use of epoll, which is efficient than poll.
In epoll unlike poll all events that need to be monitored are not passed everytime the wait call is made. Epoll uses event registration where events to be watched can be added, modified or removed. This makes it efficient when there are a large number of events to be watched.

IOLoop

In this example the class IOLoop will deal with epoll interface and it will invoke relevant handlers based on events occurred.

class IOLoop {
...
 static IOLoop * getInstance();

 IOLoop() {
  this->epfd = epoll_create(this->EPOLL_EVENTS);

  if(this->epfd < 0) {
   log_error("Failed to create epoll");
   exit(1);
  }
...
 }

 void start() {
  for(;;) {
   int nfds = epoll_wait(this->epfd, this->events, this->MAX_EVENTS, -1 /*
...

Continue reading →