aboutsummaryrefslogtreecommitdiff
path: root/connection.c
diff options
context:
space:
mode:
Diffstat (limited to 'connection.c')
-rw-r--r--connection.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/connection.c b/connection.c
new file mode 100644
index 0000000..d12ab86
--- /dev/null
+++ b/connection.c
@@ -0,0 +1,53 @@
+#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 *connectionNew(struct tsocket *sock)
+{
+ struct connection *conn = malloc(sizeof(*conn));
+ conn->sock = sock;
+
+ return conn;
+}
+
+void connectionDel(struct connection *conn)
+{
+ tsocketDelete(conn->sock);
+ free(conn);
+}
+
+int 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 ERROR;
+ } else if (n_read_bytes == -1) {
+ if (errno == EAGAIN || errno == EWOULDBLOCK)
+ break;
+ }
+ }
+
+ return OK;
+}
+
+struct event *connectionNewEvent(struct connection *conn)
+{
+ return eventNew(conn, conn->sock->fd, echo, connectionDel);
+}
+