| 1 | #include "util/mongoose.h" |
| 2 | |
| 3 | static const char* s_url = "ws://localhost:8181/websocket" ; |
| 4 | |
| 5 | // Print websocket response and signal that we're done |
| 6 | static void fn(struct mg_connection* c, int ev, void* ev_data, void* fn_data) |
| 7 | { |
| 8 | if (ev == MG_EV_OPEN) |
| 9 | { |
| 10 | c->is_hexdumping = 1; |
| 11 | } |
| 12 | else if (ev == MG_EV_CONNECT) |
| 13 | { |
| 14 | // Connected to server. Extract host name from URL |
| 15 | struct mg_str host = mg_url_host(s_url); |
| 16 | |
| 17 | // If s_url is wss://, tell client connection to use TLS |
| 18 | if (mg_url_is_ssl(s_url)) |
| 19 | { |
| 20 | struct mg_tls_opts opts = {.srvname = host}; |
| 21 | mg_tls_init(c, &opts); |
| 22 | } |
| 23 | } |
| 24 | else if (ev == MG_EV_TLS_HS) |
| 25 | { |
| 26 | MG_INFO(("TLS handshake done!" )); |
| 27 | } |
| 28 | else if (ev == MG_EV_ERROR) |
| 29 | { |
| 30 | // On error, log error message |
| 31 | MG_ERROR(("%p %s" , c->fd, (char*) ev_data)); |
| 32 | } |
| 33 | else if (ev == MG_EV_WS_OPEN) |
| 34 | { |
| 35 | // When websocket handshake is successful, send message |
| 36 | mg_ws_send(c, "hello" , 5, WEBSOCKET_OP_TEXT); |
| 37 | } |
| 38 | else if (ev == MG_EV_WS_MSG) |
| 39 | { |
| 40 | // When we get echo response, print it |
| 41 | struct mg_ws_message* wm = (struct mg_ws_message*)ev_data; |
| 42 | printf("GOT ECHO REPLY: [%.*s]\n" , (int)wm->data.len, wm->data.ptr); |
| 43 | } |
| 44 | |
| 45 | if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE || ev == MG_EV_WS_MSG) |
| 46 | { |
| 47 | // Signal that we're done |
| 48 | *(bool*)fn_data = true; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | int main(void) |
| 53 | { |
| 54 | struct mg_mgr mgr; // Event manager |
| 55 | bool done = false; // Event handler flips it to true |
| 56 | struct mg_connection* c; // Client connection |
| 57 | mg_mgr_init(&mgr); // Initialise event manager |
| 58 | mg_log_set(MG_LL_DEBUG); // Set log level |
| 59 | |
| 60 | // Create client |
| 61 | c = mg_ws_connect(&mgr, s_url, fn, &done, NULL); |
| 62 | |
| 63 | while (c && done == false) |
| 64 | { |
| 65 | // Wait for echo |
| 66 | mg_mgr_poll(&mgr, 1000); |
| 67 | } |
| 68 | |
| 69 | // Deallocate resources |
| 70 | mg_mgr_free(&mgr); |
| 71 | |
| 72 | return 0; |
| 73 | } |
| 74 | |