Banjo API 1.0.0-rc.2
Low-level C99 game development API
Loading...
Searching...
No Matches
net_tcp_client.c

TCP client: connect, send a request, read the reply.

TCP client: connect, send a request, read the reply.Demonstrates: bj_resolve_address, bj_connect_tcp, bj_tcp_send, bj_tcp_recv. Pair with net_tcp_server.c to test.

#include <banjo/log.h>
#include <banjo/main.h>
#include <banjo/net.h>
#include <banjo/system.h>
#include <string.h>
int main(int argc, char* argv[]) {
(void)argc;
(void)argv;
return -1;
}
struct bj_error* error = 0;
bj_info("client: connecting to 127.0.0.1:8080...");
struct bj_tcp_stream* stream = bj_connect_tcp("127.0.0.1", 8081, 0, 3000, &error);
if (!stream) {
bj_err("client: connect failed (%s)", bj_error_message(error));
bj_clear_error(&error);
return 1;
}
bj_info("client: connected to server");
const char* name = "Banjo";
bj_info("client: sending name: %s", name);
bj_tcp_send(stream, name, strlen(name));
char buf[512];
int n = bj_tcp_recv(stream, buf, sizeof(buf) - 1);
if (n > 0) {
buf[n] = '\0';
bj_info("client: server replied: %s", buf);
}
bj_info("client: connection closed");
bj_end();
return 0;
}
int main(int argc, char *argv[])
Definition audio_pcm.c:177
struct bj_error bj_error
Definition api.h:333
struct bj_tcp_stream bj_tcp_stream
Definition api.h:357
const char * bj_error_message(const struct bj_error *error)
Gets the error message from an error object.
void bj_clear_error(struct bj_error **error)
Frees an error and sets the pointer to NULL.
#define bj_info(...)
Log a message using the BJ_LOG_INFO level.
Definition log.h:141
#define bj_err(...)
Log a message using the BJ_LOG_ERROR level.
Definition log.h:169
int bj_tcp_recv(struct bj_tcp_stream *stream, void *buf, size_t len)
Receives data from a TCP stream.
void bj_close_tcp_stream(struct bj_tcp_stream *stream)
Closes a TCP stream and releases associated resources.
int bj_tcp_send(struct bj_tcp_stream *stream, const void *buf, size_t len)
Sends data over a TCP stream.
struct bj_tcp_stream * bj_connect_tcp(const char *host, uint16_t port, uint16_t hint, uint32_t ms_timeout, struct bj_error **error)
Connects to a TCP server at the specified host and port.
bj_bool bj_begin(int systems, struct bj_error **error)
Initialises the system.
void bj_end(void)
De-initialises the system.
@ BJ_NETWORK_SYSTEM
Definition system.h:82
Logging utility functions.
Portable main() replacement with platform-aware entry shim.
Header file for network API.
String utility functions.
Header file for system interactions.