From 9bed42bfcdb548c2f097a7536d3fa6a4117b57e9 Mon Sep 17 00:00:00 2001 From: Guangxiong Lin Date: Thu, 1 Dec 2022 23:40:27 +0800 Subject: Save sockets inside epoll data --- eventloop.c | 8 ++------ eventloop.h | 1 - server.c | 8 +++----- 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/eventloop.c b/eventloop.c index f79114d..9a26b98 100644 --- a/eventloop.c +++ b/eventloop.c @@ -19,10 +19,7 @@ int eventLoopAddSocket(struct eventLoop *el, struct tsocket *sock, int flag) { struct epoll_event ev; ev.events = flag; - ev.data.fd = sock->fd; - - // TODO: How the fd ranges? Will it be larger than the MAX_EVENTS? - el->socks[sock->fd] = sock; + ev.data.ptr = sock; return epoll_ctl(el->epollfd, EPOLL_CTL_ADD, sock->fd, &ev); } @@ -34,6 +31,5 @@ int eventLoopWait(struct eventLoop *el, int timeout) struct tsocket *eventLoopGetSocket(struct eventLoop *el, int index) { - int fd = el->events[index].data.fd; - return el->socks[fd]; + return (struct tsocket *)el->events[index].data.ptr; } diff --git a/eventloop.h b/eventloop.h index 39c05d5..4dd7f6e 100644 --- a/eventloop.h +++ b/eventloop.h @@ -10,7 +10,6 @@ struct eventLoop { int epollfd; struct epoll_event events[EVENT_LOOP_MAX_EVENTS]; - struct tsocket *socks[EVENT_LOOP_MAX_EVENTS]; int size; }; diff --git a/server.c b/server.c index 1e3ad68..bc856f9 100644 --- a/server.c +++ b/server.c @@ -69,18 +69,16 @@ int main() if (conn_sock == NULL) panic("socket accept error"); - printf("New client fd %d, ip: %s, port: %d\n", - conn_sock->fd, conn_sock->addr, conn_sock->port); - if (setblocking(conn_sock->fd, false) == -1) { - close(conn_sock->fd); + tsocketDelete(conn_sock); continue; } if (eventLoopAddSocket(el, conn_sock, EPOLLIN | EPOLLET) == -1) panic("eventloop add fd: conn_sockfd"); - tsocketDelete(conn_sock); + printf("New client fd %d, ip: %s, port: %d\n", + conn_sock->fd, conn_sock->addr, conn_sock->port); } else { handleEvent(eventLoopGetSocket(el, i)); } -- cgit v1.2.3