// 하앍 include 가 넘 많다...
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>

#define EPOLL_SIZE 60
#define EPOLL_EVENT_SIZE 100
#define OPENPORT 5000

// main
int
main (int argc, char **argv)
{
 struct epoll_event *events;
 struct epoll_event ev;
 struct sockaddr_in addr, clientaddr;
 int clilen;
 int sfd, efd, cfd;
 int i;
 int max_got_events;
 int result;
 int readn;
 int sendflags = 0;
 char buf_in[256] = { '\0' };

 if ((efd = epoll_create (EPOLL_EVENT_SIZE)) < 0)
 {
  perror ("epoll_create (1) error");
  return -1;
 }
 
 // init pool
 events = (struct epoll_event *) malloc (sizeof (*events) * EPOLL_SIZE);
 if (NULL == events)
 {
  perror ("epoll_create (0) error");
  return -1;
 }

 clilen = sizeof (clientaddr);
 sfd = socket (AF_INET, SOCK_STREAM, 0);
 if (sfd == -1)
 {
  perror ("socket error :");
  close (sfd);
  return -1;
 }

 addr.sin_family = AF_INET;
 addr.sin_port = htons (OPENPORT);
 addr.sin_addr.s_addr = htonl (INADDR_ANY);
 if (bind (sfd, (struct sockaddr *) &addr, sizeof (addr)) == -1)
 {
  close (sfd);
  return -2;
 }
 listen (sfd, 5);
 
 if (sfd < 0)
 {
  perror ("init_acceptsock error");
  return 1;
 }

 printf("Running Server port %d\n",port);
 ev.events = EPOLLIN;
 ev.data.fd = sfd;
 result = epoll_ctl (efd, EPOLL_CTL_ADD, sfd, &ev);
 if (result < 0)
 {
  perror ("epoll_ctl error");
  return 1;
 }

 while (1)
 {
  max_got_events = epoll_wait (efd, events, EPOLL_SIZE, -1);
  for (i = 0; i < max_got_events; i++)
  {
   if (events[i].data.fd == sfd)
   {
    printf("Accepted\n");
    cfd = accept (sfd, (struct sockaddr *) &clientaddr, &clilen);
    if (cfd < 0)
    {
     perror ("Accept error");
     return -1;
    }

    ev.events = EPOLLIN;
    ev.data.fd = cfd;
    epoll_ctl (efd, EPOLL_CTL_ADD, cfd, &ev);
   }
   else
   {
    cfd = events[i].data.fd;

    memset (buf_in, 0x00, 256);
    readn = read (cfd, buf_in, 255);
    // if it occured ploblems with reading, delete from epoll event pool and close socket
    if (readn <= 0)
    {
     epoll_ctl (efd, EPOLL_CTL_DEL, cfd, &ev);
     close (cfd);
     printf ("Close fd ", cfd);
    }
    else
    {
     printf ("%s", buf_in);
     send (cfd, buf_in, strlen (buf_in), sendflags);
    }

   }
  }
 }
 return 1;
}

'리눅스 서버에 대해서' 카테고리의 다른 글

Epoll 채팅 서버 소스  (0) 2008.05.25
Select 채팅 서버  (0) 2008.05.25
쓰레드 에코서버  (0) 2008.05.25
epoll 서버 프로그래밍  (0) 2008.03.29
겜서버 숙제  (0) 2008.03.24

+ Recent posts