aboutsummaryrefslogtreecommitdiff
path: root/src/connection.c
diff options
context:
space:
mode:
authorGuangxiong Lin <[email protected]>2022-12-16 13:53:35 +0800
committerGuangxiong Lin <[email protected]>2022-12-16 13:53:35 +0800
commit7369505397cdfddf0883e2c24e1652df8bd488fe (patch)
treee961bd1bba0276e2c5f523bf12663b34983c9e51 /src/connection.c
parent49839c88a98d3798f7b18c58f54f26f36cacff38 (diff)
downloadtinyserver-7369505397cdfddf0883e2c24e1652df8bd488fe.tar.gz
tinyserver-7369505397cdfddf0883e2c24e1652df8bd488fe.tar.bz2
tinyserver-7369505397cdfddf0883e2c24e1652df8bd488fe.zip
Refactor file structure
Diffstat (limited to 'src/connection.c')
-rw-r--r--src/connection.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/connection.c b/src/connection.c
new file mode 100644
index 0000000..c164ec8
--- /dev/null
+++ b/src/connection.c
@@ -0,0 +1,58 @@
+#include <stdlib.h>
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "connection.h"
+#include "constant.h"
+
+#define READ_BUFFER_SIZE 1024
+
+struct connection {
+ struct tsocket *sock;
+};
+
+struct connection *connection_create(struct tsocket *sock)
+{
+ struct connection *conn = malloc(sizeof(*conn));
+ conn->sock = sock;
+
+ return conn;
+}
+
+void connection_destroy(struct connection *conn)
+{
+ tsocket_destroy(conn->sock);
+ free(conn);
+}
+
+static void echo(struct connection *conn)
+{
+ char buf[READ_BUFFER_SIZE];
+ ssize_t n_read_bytes;
+
+ struct tsocket *sock = (struct tsocket *)conn->sock;
+
+ 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);
+ return;
+ } else if (n_read_bytes == -1) {
+ if (errno == EAGAIN || errno == EWOULDBLOCK)
+ break;
+ }
+ }
+}
+
+event_t *connection_create_event(struct tsocket *sock)
+{
+ connection_t *conn = connection_create(sock);
+ return event_create(conn, conn->sock->fd,
+ (evloop_process_func_t) echo,
+ (evloop_destroy_func_t) connection_destroy);
+}
+