fnet.c

Simple C networking library
git clone git://git.finwo.net/lib/fnet.c
Log | Files | Refs | README

commit b3c8ca014e7837fe0df52e28d9c041b277033d28
parent c9f73341bf3a66d349ca8549cf24f43c2b7334c4
Author: Yersa Nordman <yersa@finwo.nl>
Date:   Tue,  1 Aug 2023 22:49:38 +0200

Implemented write and test echo server

Diffstat:
Msrc/fnet.c | 34++++++++++++++++++++++++++++++++++
Msrc/fnet.h | 1+
Mtest.c | 3+++
3 files changed, 38 insertions(+), 0 deletions(-)

diff --git a/src/fnet.c b/src/fnet.c @@ -360,6 +360,40 @@ FNET_RETURNCODE fnet_write(const struct fnet_t *connection, struct buf *buf) { return FNET_RETURNCODE_MISSING_ARGUMENT; } + // A listening socket is not a connection + if (conn->ext.status & FNET_STATUS_LISTENING) { + fprintf(stderr, "fnet_write: Writing to a listening socket is not possible\n"); + return FNET_RETURNCODE_UNPROCESSABLE; + } + + // How would I do this?? :S + if (conn->nfds > 1) { + fprintf(stderr, "fnet_write: Only connections with 1 file descriptor supported\n"); + return FNET_RETURNCODE_NOT_IMPLEMENTED; + } + if (conn->nfds < 1) { + fprintf(stderr, "fnet_write: Only connections with 1 file descriptor supported\n"); + return FNET_RETURNCODE_NOT_IMPLEMENTED; + } + + int n = 0; + ssize_t r; + while(n < buf->len) { + r = write(conn->fds[0], &(buf->data[n]), buf->len - n); + // Handle errors + if (r < 0) { + if (errno == EAGAIN) { + continue; // Try again + } + // We don't have a way to handle this error (yet) + fprintf(stderr, "fnet_write: Unable to write to connection\n"); + return FNET_RETURNCODE_ERRNO; + } + // Increment counter with amount of bytes written + // Allows for a partial write to not corrupt the data stream + n += r; + } + return FNET_RETURNCODE_OK; } diff --git a/src/fnet.h b/src/fnet.h @@ -21,6 +21,7 @@ extern "C" { #define FNET_RETURNCODE_MISSING_ARGUMENT -2 #define FNET_RETURNCODE_NOT_IMPLEMENTED -3 #define FNET_RETURNCODE_ERRNO -4 +#define FNET_RETURNCODE_UNPROCESSABLE -5 #define FNET_STATUS uint8_t #define FNET_STATUS_INITIALIZING 0 diff --git a/test.c b/test.c @@ -10,6 +10,9 @@ void onClose(struct fnet_ev *ev) { void onData(struct fnet_ev *ev) { printf("Data(%d): %.*s\n", ev->buffer->len, (int)(ev->buffer->len), ev->buffer->data); + + // Simple echo + fnet_write(ev->connection, ev->buffer); } void onConnect(struct fnet_ev *ev) {