tcp-chat/src/network/socket.h

49 lines
2.0 KiB
C
Executable File

#pragma once
#include "endpoint.h"
#include "tlibc/errors.h"
#include "tlibc/time.h"
#include "tlibc/collections/Array.h"
typedef enum SocketShutdownType {
SocketShutdownType_Receive = 0,
SocketShutdownType_Send = 1,
SocketShutdownType_Both = 2,
} SocketShutdownType;
typedef enum SocketRecvFlag {
SocketRecvFlag_None = 0,
SocketRecvFlag_Peek = 0b1 /* next recv call will read the same data */,
SocketRecvFlag_WholeBuffer = 0b10 /* waits until buffer is full */,
} SocketRecvFlag;
typedef i64 Socket;
Result(Socket) socket_open_TCP();
void socket_close(Socket s);
Result(void) socket_shutdown(Socket s, SocketShutdownType direction);
Result(void) socket_bind(Socket s, EndpointIPv4 local_end);
Result(void) socket_listen(Socket s, i32 backlog);
Result(Socket) socket_accept(Socket listening_sock, NULLABLE(EndpointIPv4*) remote_end);
Result(void) socket_connect(Socket s, EndpointIPv4 remote_end);
Result(void) socket_send(Socket s, Array(u8) buffer);
Result(void) socket_sendto(Socket s, Array(u8) buffer, EndpointIPv4 dst);
Result(i32) socket_recv(Socket s, Array(u8) buffer, SocketRecvFlag flags);
Result(i32) socket_recvfrom(Socket s, Array(u8) buffer, SocketRecvFlag flags, NULLABLE(EndpointIPv4*) remote_end);
/// Enables sending SO_KEEPALIVE packets when socket is idling.
/// Also enables TCP_USER_TIMEOUT to handle situations
/// when socket is not sending KEEPALIVE packets.
/// Read more: https://blog.cloudflare.com/when-tcp-sockets-refuse-to-die/
/// RU translaton: https://habr.com/ru/articles/700470/
Result(void) socket_TCP_enableAliveChecks(Socket s,
sec_t first_check_time, u32 checks_count, sec_t checks_interval);
#define socket_TCP_enableAliveChecks_default(socket) \
socket_TCP_enableAliveChecks(socket, 1, 4, 5)
#define SOCKET_TIMEOUT_MS_DEFAULT 5000
#define SOCKET_TIMEOUT_MS_INFINITE 0
/// @brief sets general timeout for send() and recv()
Result(void) socket_setTimeout(Socket s, u32 ms);