void ServerModel::recive(const struct EpollMessage* _msg) { if(_msg->fd == getSockFd()) { listen(_msg); } else { reciveMsg(_msg); } }
void ServerModel::listen(const struct EpollMessage* _msg) { sock::Acceptor* client = new sock::Acceptor(getSockFd(), new struct sockaddr_in()); client->active(); int socket = client->getSock(); memset(_msg->ctl, 0x00, sizeof(struct epoll_event)); _msg->ctl->events = EPOLLIN; _msg->ctl->data.ptr = new std::shared_ptr<sock::Sock>(client); epoll_ctl(m_epoll, EPOLL_CTL_ADD, socket, _msg->ctl); connect(); }
/* * Steps of working: * 1 - Port number is accepted via command line args * 2 - Server Socket is created * 3 - A single client is allowed to connect, followed by creation of a client socket * 4 - Message is read from the client * 5 - A message is sent to the client in response * 6 - Client socket is closed * 7 - Go back to step 3 * * --------------------------------- * If the program is terminated: * 8 - Server socket is closed * 9 - Program terminates */ int main(int argc, char *argv[]) { int portNo = atoi(argv[1]); int sockFd = getSockFd(portNo); int clientFd; char buff[MAX_BUFF]; char *headers; char *msg; char *response; int n; int clientCounter = 0; // Running this loop forever... while(1) { clientCounter++; clientFd = getClientFd(sockFd); // Waiting for the client to connect. n = read(clientFd, buff, MAX_BUFF - 1); // Reading what client has to say. printf("%s\r\n", buff); // Printing the message received from the client. msg = (char *)calloc(MAX_BUFF, sizeof(char)); headers = (char *)calloc(MAX_BUFF, sizeof(char)); sprintf(msg, "Hi, Client number %d!\r\n", clientCounter); sprintf(headers, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %lu\r\n\r\n", strlen(msg)); response = (char *)calloc(MAX_BUFF + MAX_BUFF, sizeof(char)); response = strcat(headers, msg); n = write(clientFd, response, strlen(response)); // Writing a response message for the client close(clientFd); // Closing the client connection. } close(sockFd); return 0; }