From 8693eef8febde4df90b7fbd1fb9ac813b132fa50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Manuel=20Tom=C3=A1s?= Date: Mon, 20 Jul 2020 01:50:14 -0300 Subject: Wrap external functionality into classes --- src/server/jet.cpp | 71 ++++++++++++------------------------------------------ 1 file changed, 16 insertions(+), 55 deletions(-) (limited to 'src/server/jet.cpp') diff --git a/src/server/jet.cpp b/src/server/jet.cpp index 5cc3ee4..e29005a 100644 --- a/src/server/jet.cpp +++ b/src/server/jet.cpp @@ -1,72 +1,33 @@ #include -#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include - #include +#include +#include + #include #include #include #include -#define PORT 6969 -#define MAX_EVENTS 10 +Client *clients[1024] = {}; +Buffer scratch("scratch"); + +void new_connection(int fd) { + if (clients[fd]) { + delete clients[fd]; + } + clients[fd] = new Client(scratch, fd); +} -int create_listener() { - int s = socket(AF_INET, SOCK_STREAM, 0); - sockaddr_in addr = { AF_INET, htons(PORT), htonl(INADDR_LOOPBACK)}; - int opt = 1; - setsockopt(s, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)); - bind(s, (sockaddr *) &addr, sizeof(sockaddr_in)); - listen(s, MAX_EVENTS); - return s; +void existing_connection(int fd) { + clients[fd]->parse_message(); } int main() { - Buffer scratch("scratch"); scratch.read_file("test.txt"); - int listener = create_listener(); - - int epollfd = epoll_create1(0); - - epoll_event ev; - ev.events = EPOLLIN; - ev.data.fd = listener; - epoll_ctl(epollfd, EPOLL_CTL_ADD, listener, &ev); - - epoll_event events[MAX_EVENTS]; - Client *clients[1024] = {}; - - while (true) { - int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); - - for (int i = 0; i < nfds; i++) { - if (events[i].data.fd == listener) { - int clientfd = accept(listener, 0, 0); - ev.events = EPOLLIN | EPOLLET; - ev.data.fd = clientfd; - if (clients[clientfd]) { - delete clients[clientfd]; - } - Client *c = new Client(scratch); - c->sockfd = clientfd; - clients[clientfd] = c; - epoll_ctl(epollfd, EPOLL_CTL_ADD, clientfd, &ev); - } else { - clients[events[i].data.fd]->parse_message(); - } - } - } - - close(listener); + Socket listener; + listener.listen(new_connection, existing_connection); } -- cgit v1.2.3