Created
September 4, 2025 14:00
-
-
Save cpq/1e2011a22a91f4f822ad0259e316a81a to your computer and use it in GitHub Desktop.
Example mongoose tcp client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include "mongoose.h" | |
| // Public TCP echo server, see https://tcpbin.com/ | |
| #define TCP_SERVER_URL "tcp://tcpbin.com:4242" | |
| // Custom TCP protocol client connection | |
| static struct mg_connection *s_client_conn = NULL; | |
| static void tcp_ev_handler(struct mg_connection *c, int ev, void *ev_data) { | |
| if (ev == MG_EV_OPEN) { | |
| // Connection is created. Set hexdump flag for debugging | |
| c->is_hexdumping = 1; | |
| } else if (ev == MG_EV_READ) { | |
| // Process received TCP data | |
| MG_INFO(("Received: %.*s", c->recv.len, c->recv.buf)); | |
| c->recv.len = 0; // Discard received data | |
| } else if (ev == MG_EV_CLOSE) { | |
| s_client_conn = NULL; | |
| } | |
| } | |
| static void timer_fn(void *arg) { | |
| struct mg_mgr *mgr = (struct mg_mgr *) arg; | |
| if (s_client_conn == NULL) { | |
| // TCP client is not connected. Reconnect | |
| s_client_conn = mg_connect(mgr, TCP_SERVER_URL, tcp_ev_handler, NULL); | |
| } else { | |
| // TCP client is connected. Send some message to it | |
| mg_printf(s_client_conn, "Hi! Current time is %llu\n", mg_now()); | |
| } | |
| } | |
| int main(void) { | |
| struct mg_mgr mgr; | |
| mg_mgr_init(&mgr); | |
| mg_timer_add(&mgr, 2500, MG_TIMER_REPEAT, timer_fn, &mgr); | |
| for (;;) { | |
| mg_mgr_poll(&mgr, 100); | |
| } | |
| mg_mgr_free(&mgr); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment