diff options
author | mrfoxygmfr <mrfoxygmfr@sch9.ru> | 2025-05-21 02:34:56 +0300 |
---|---|---|
committer | mrfoxygmfr <mrfoxygmfr@sch9.ru> | 2025-05-21 02:34:56 +0300 |
commit | af138ab46ef4dd303d873c05542bb434859225a7 (patch) | |
tree | 5fa5daaea90108a943241f7728ba4144f3a951e5 | |
parent | 7e0a1e2904c03c8550c8117b43f4d54a3d742258 (diff) |
feat(lib/net): implement read and write for connection
-rw-r--r-- | lib/net/common.c | 49 | ||||
-rw-r--r-- | lib/net/common.h | 2 |
2 files changed, 51 insertions, 0 deletions
diff --git a/lib/net/common.c b/lib/net/common.c index d3ed0b3..152c5c0 100644 --- a/lib/net/common.c +++ b/lib/net/common.c @@ -61,3 +61,52 @@ int conn_configure_tcpalive(conn_t* conn) { return 1; } + +char* conn_read(conn_t* conn, size_t* size) { + size_t sz; + int n = recv(conn->conn_socket_fd, &sz, sizeof(sz), 0); + if (n == 0) { + *size = 0; + return NULL; + } + + if (n != sizeof(sz)) { + fprintf(stderr, "[conn_read] Failed to read size of msg %d %d\n", n, errno); + exit(EXIT_FAILURE); + } + + char* buf = calloc(sz, sizeof(*buf)); + + size_t readed = 0; + while (readed < sz) { + int n = recv(conn->conn_socket_fd, buf + readed, sz - readed, MSG_WAITALL); + if (n == -1) { + fprintf(stderr, "[conn_read] Failed to read msg\n"); + exit(EXIT_FAILURE); + } + + readed += n; + } + + *size = readed; + return buf; +} + +void conn_write(conn_t* conn, const char* value, size_t sz) { + int n = write(conn->conn_socket_fd, &sz, sizeof(sz)); + if (n != sizeof(sz)) { + fprintf(stderr, "[conn_write] Failed to write size of msg\n"); + exit(EXIT_FAILURE); + } + + size_t written = 0; + while (written < sz) { + int n = write(conn->conn_socket_fd, value + written, sz - written); + if (n == -1) { + fprintf(stderr, "[conn_write] Failed to write msg\n"); + exit(EXIT_FAILURE); + } + + written += n; + } +} diff --git a/lib/net/common.h b/lib/net/common.h index f7c4c9a..553117d 100644 --- a/lib/net/common.h +++ b/lib/net/common.h @@ -14,6 +14,8 @@ typedef struct { struct sockaddr_in* get_addr(const char* addr, const char* port); int conn_configure_tcpalive(conn_t* conn); +char* conn_read(conn_t* conn, size_t* sz); +void conn_write(conn_t* conn, const char* value, size_t sz); void conn_close(conn_t* conn); #endif // NET__COMMON_H |