#include #include #include #include #include #include #include #include #include #include #include #include "eventloop.h" #include "tsocket.h" #include "util.h" #define READ_BUFFER_SIZE 1024 void handleEvent(struct tsocket *sock) { char buf[READ_BUFFER_SIZE]; ssize_t n_read_bytes; for (;;) { n_read_bytes = read(sock->fd, buf, sizeof(buf)); if (n_read_bytes > 0) { printf("message from conn %d: %s\n", sock->fd, buf); write(sock->fd, buf, sizeof(buf)); } else if (n_read_bytes == 0) { printf("conn %d disconnected\n", sock->fd); tsocketDelete(sock); break; } else if (n_read_bytes == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; } } } int main() { struct tsocket *sock = tsocketNew(); if (sock == NULL) panic("socket creation error"); if (tsocketBind(sock, "127.0.0.1", 8888) == -1) panic("socket bind error"); if (tsocketListen(sock) == -1) panic("socket listen error"); struct eventLoop *el = eventLoopNew(); if (el == NULL) panic("eventloop creation"); if (eventLoopAddSocket(el, sock, EPOLLIN) == -1) panic("eventloop add fd"); int nfds; struct tsocket *conn_sock; for (;;) { nfds = eventLoopWait(el, -1); if (nfds == -1) panic("eventloop wait"); for (int i = 0; i < nfds; i++) { if (eventLoopGetSocket(el, i) == sock) { conn_sock = tsocketAccept(sock); if (conn_sock == NULL) panic("socket accept error"); if (setblocking(conn_sock->fd, false) == -1) { tsocketDelete(conn_sock); continue; } if (eventLoopAddSocket(el, conn_sock, EPOLLIN | EPOLLET) == -1) panic("eventloop add fd: conn_sockfd"); printf("New client fd %d, ip: %s, port: %d\n", conn_sock->fd, conn_sock->addr, conn_sock->port); } else { handleEvent(eventLoopGetSocket(el, i)); } } } }