aboutsummaryrefslogtreecommitdiff
path: root/example/server.c
diff options
context:
space:
mode:
authorGuangxiong Lin <[email protected]>2022-12-17 21:24:04 +0800
committerGuangxiong Lin <[email protected]>2022-12-17 21:53:40 +0800
commite339f2d269fcaffed7beed67c3995fe3b67393eb (patch)
treef1a94f746808d2e90023b0d0cdbc8307b5648f88 /example/server.c
parent7bb3515bc303a2a35fe859bcdba2795fbe06643d (diff)
downloadtinyserver-master.tar.gz
tinyserver-master.tar.bz2
tinyserver-master.zip
Support on_connect function in server libHEADmaster
Diffstat (limited to 'example/server.c')
-rw-r--r--example/server.c36
1 files changed, 36 insertions, 0 deletions
diff --git a/example/server.c b/example/server.c
new file mode 100644
index 0000000..fe8cba9
--- /dev/null
+++ b/example/server.c
@@ -0,0 +1,36 @@
+#include <errno.h>
+#include <unistd.h>
+#include <stdio.h>
+
+#include "../src/server.h"
+#include "../src/connection.h"
+
+#define READ_BUFFER_SIZE 1024
+
+static void echo(connection_t *conn)
+{
+ char buf[READ_BUFFER_SIZE];
+ ssize_t n_read_bytes;
+ int fd = connection_fd(conn);
+
+ for (;;) {
+ n_read_bytes = read(fd, buf, sizeof(buf));
+ if (n_read_bytes > 0) {
+ printf("message from conn %d: %s\n", fd, buf);
+ write(fd, buf, sizeof(buf));
+ } else if (n_read_bytes == 0) {
+ printf("conn %d disconnected\n", fd);
+ return;
+ } else if (n_read_bytes == -1) {
+ if (errno == EAGAIN || errno == EWOULDBLOCK)
+ break;
+ }
+ }
+}
+
+int main()
+{
+ server_t *serv = server_create();
+ server_on_connect(serv, echo);
+ server_run(serv);
+}