ServerHandler will create a server socket and handle in coming connections
class ServerHandler : Handler {
...
ServerHandler(int port) {
memset(&addr, 0, sizeof(addr));
if ((fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
log_error("Failed to create server socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (bind(fd, (struct sockaddr *) &addr,
sizeof(addr)) < 0) {
log_error("Failed to bind server socket");
exit(1);
}
if (listen(fd, MAX_PENDING) < 0) {
log_error("Failed to listen on server socket");
exit(1);
}
setnonblocking(fd);
IOLoop::getInstance()->addHandler(fd, this, EPOLLIN);
}
virtual int handle(epoll_event e) {
sockaddr_in client_addr;
socklen_t ca_len = sizeof(client_addr);
int client = accept(fd, (struct sockaddr *) &client_addr,
&ca_len);
if(client < 0) {
log_error("Error accepting connection");
return -1;
}
cout << "Client connected: " << inet_ntoa(client_addr.sin_addr) << endl;
new EchoHandler(client, client_addr);
return 0;
}
};