Skip to content

Instantly share code, notes, and snippets.

@luoyetx
Created March 28, 2016 13:13
Show Gist options
  • Select an option

  • Save luoyetx/eb85cb4ca7202b3eef8f to your computer and use it in GitHub Desktop.

Select an option

Save luoyetx/eb85cb4ca7202b3eef8f to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
typedef struct {
int fd;
int msg_len;
char *msg;
} EchoEvent;
int make_non_blocking(int fd) {
int flags;
flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
return 0;
}
int main(int argc, char *argv[]) {
int efd, sfd;
struct sockaddr_in addr = { 0 };
sfd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(8080);
int r = bind(sfd, (struct sockaddr*)&addr, sizeof(addr));
printf("%d\n", r);
make_non_blocking(sfd);
listen(sfd, 10);
char msg[] = "listen at 8080\n";
write(1, msg, sizeof(msg));
efd = epoll_create1(0);
int evs_n = 10;
struct epoll_event ev;
struct epoll_event evs[10];
ev.data.fd = sfd;
ev.events = EPOLLIN | EPOLLET;
epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &ev);
int buff_size = 300;
char buff[310];
while (1) {
int n, i;
n = epoll_wait(efd, evs, evs_n, -1);
printf("%d\n", n);
for (i=0; i<n; i++) {
if (evs[i].data.fd == sfd) {
char *msg = "get a connection\n";
printf("%s", msg);
int len = sizeof(addr);
int cli_fd = accept(sfd, (struct sockaddr*)&addr, &len);
make_non_blocking(cli_fd);
ev.data.fd = cli_fd;
ev.events = EPOLLIN | EPOLLET;
epoll_ctl(efd, EPOLL_CTL_ADD, cli_fd, &ev);
}
else if (evs[i].events & EPOLLIN) {
int c;
c = read(evs[i].data.fd, buff, buff_size);
if (c == 0) {
char *msg = "remote close";
printf("%s\n", msg);
close(evs[i].data.fd);
continue;
}
write(1, buff, c);
//ev.data.fd = evs[i].data.fd;
//ev.events = EPOLLOUT | EPOLLET;
//epoll_ctl(efd, EPOLL_CTL_MOD, ev.data.fd, &ev);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment