SHARE
TWEET

Untitled

a guest Nov 22nd, 2019 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <sys/socket.h>
  4. #include <stdlib.h>
  5. #include <netinet/in.h>
  6. #include <string.h>
  7. #include <sys/epoll.h>
  8. #include <iostream>
  9. #include "TcpServer.h"
  10.  
  11.  
  12. int main(int argc, char const *argv[]) {
  13. #define MAX_EVENTS 10
  14.     struct epoll_event ev, events[MAX_EVENTS];
  15.     int nfds, conn_sock, epollfd;
  16.  
  17.     int server_fd, new_socket, valread;
  18.     struct sockaddr_in address;
  19.     int addrlen = sizeof(address);
  20.     char buffer[1024] = {0};
  21.  
  22.     if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
  23.         perror("socket failed");
  24.         exit(EXIT_FAILURE);
  25.     }
  26.  
  27.     address.sin_family = AF_INET;
  28.     address.sin_addr.s_addr = INADDR_ANY;
  29.     address.sin_port = htons(PORT);
  30.  
  31.     if (bind(server_fd, (struct sockaddr *) &address,
  32.              sizeof(address)) < 0) {
  33.         perror("bind failed");
  34.         exit(EXIT_FAILURE);
  35.     }
  36.     if (listen(server_fd, 3) < 0) {
  37.         perror("listen");
  38.         exit(EXIT_FAILURE);
  39.     }
  40.     epollfd = epoll_create1(0);
  41.     if (epollfd == -1) {
  42.         perror("epoll_create1");
  43.         exit(EXIT_FAILURE);
  44.     }
  45.  
  46.     ev.events = EPOLLIN;
  47.     ev.data.fd = server_fd;
  48.     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, server_fd, &ev) == -1) {
  49.         perror("epoll_ctl: server_fd");
  50.         exit(EXIT_FAILURE);
  51.     }
  52.  
  53.     for (;;) {
  54.         nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
  55.  
  56.         for (int n = 0; n < nfds; ++n) {
  57.             if (events[n].data.fd == server_fd) {
  58.                 conn_sock = accept(server_fd, (struct sockaddr *) &address,
  59.                                    (socklen_t *) &addrlen);
  60.                 ev.events = EPOLLIN | EPOLLET;
  61.                 ev.data.fd = conn_sock;
  62.                 epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev);
  63.                 int len = read(events[n].data.fd, buffer, 1024);
  64.                 write(events[n].data.fd, buffer, len);
  65.             }
  66.         }
  67.     }
  68. // nc -v localhost 8081
  69.     return 0;
  70. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top