aboutsummaryrefslogtreecommitdiff
path: root/server.c
diff options
context:
space:
mode:
Diffstat (limited to 'server.c')
-rw-r--r--server.c93
1 files changed, 8 insertions, 85 deletions
diff --git a/server.c b/server.c
index bab1edc..f4ad78d 100644
--- a/server.c
+++ b/server.c
@@ -13,88 +13,8 @@
#include "eventloop.h"
#include "tsocket.h"
#include "util.h"
-
-#define READ_BUFFER_SIZE 1024
-
-void handleReadEvent(struct event *ev)
-{
- char buf[READ_BUFFER_SIZE];
- ssize_t n_read_bytes;
-
- struct tsocket *sock = (struct tsocket *)ev->data;
-
- 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);
- eventLoopDel(ev->el, ev);
- break;
- } else if (n_read_bytes == -1) {
- if (errno == EAGAIN || errno == EWOULDBLOCK)
- break;
- }
- }
-}
-
-void serverDeleteReadEvent(struct event *ev)
-{
- tsocketDelete(ev->data);
- free(ev);
-}
-
-struct event *serverNewReadEvent(struct tsocket *sock)
-{
- struct event *ev = malloc(sizeof(*ev));
- ev->data = sock;
- ev->handle = handleReadEvent;
- ev->fd = sock->fd;
- ev->delete = serverDeleteReadEvent;
-
- return ev;
-}
-
-void handleNewClientConnection(struct event *ev)
-{
- struct tsocket *conn_sock = tsocketAccept(ev->data);
- if (conn_sock == NULL) {
- perror("socket accept");
- return;
- }
-
- if (setblocking(conn_sock->fd, false) == -1) {
- perror("setblocking");
- tsocketDelete(conn_sock);
- return;
- }
-
- struct event *read_ev = serverNewReadEvent(conn_sock);
- if (eventLoopAdd(ev->el, read_ev, EPOLLIN | EPOLLET) == -1) {
- perror("eventloop add fd: conn_sock");
- return;
- }
-
- printf("New client fd %d, ip: %s, port: %d\n",
- conn_sock->fd, conn_sock->addr, conn_sock->port);
-}
-
-struct event *serverNewAcceptEvent(const char *addr, int port)
-{
- struct tsocket *sock = tsocketNew();
- if (sock == NULL
- || tsocketBind(sock, addr, port) == -1
- || tsocketListen(sock) == -1)
- return NULL;
-
- struct event *ev = malloc(sizeof(*ev));
- ev->handle = handleNewClientConnection;
- ev->data = sock;
- ev->fd = sock->fd;
-
- return ev;
-}
+#include "connection.h"
+#include "acceptor.h"
int main()
{
@@ -102,10 +22,13 @@ int main()
if (el == NULL)
panic("eventloop creation");
- struct event *acceptEvent = serverNewAcceptEvent("127.0.0.1", 8888);
- if (acceptEvent == NULL)
- panic("server client connection event");
+ struct tsocket *sock = tsocketNew();
+ if (sock == NULL
+ || tsocketBind(sock, "127.0.0.1", 8888) == -1
+ || tsocketListen(sock) == -1)
+ panic("socket creation");
+ struct event *acceptEvent = connAcceptorNewEvent(sock, el);
if (eventLoopAdd(el, acceptEvent, EPOLLIN) == -1)
panic("eventloop add fd");