| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | #include "websocket-echo.h" |
| 4 | |
| 5 | // Called when a client is connected and ready to exchange messages |
| 6 | void echo_on_connect(struct websocket_server_client *wsc) { |
| 7 | if (!wsc) return; |
| 8 | |
| 9 | websocket_debug(wsc, "Echo protocol client connected"); |
| 10 | |
| 11 | // Send a welcome message |
| 12 | // websocket_protocol_send_text(wsc, "Welcome to Netdata Echo WebSocket Server"); |
| 13 | } |
| 14 | |
| 15 | // Called when a message is received from the client |
| 16 | void echo_on_message_callback(struct websocket_server_client *wsc, const char *message, size_t length, WEBSOCKET_OPCODE opcode) { |
| 17 | if (!wsc || !message) |
| 18 | return; |
| 19 | |
| 20 | websocket_debug(wsc, "Echo protocol handling message: type=%s, length=%zu", |
| 21 | (opcode == WS_OPCODE_BINARY) ? "binary" : "text", |
| 22 | length); |
| 23 | |
| 24 | // Simply echo back the same message with the same opcode |
| 25 | // Use send_payload to automatically handle large messages with fragmentation |
| 26 | websocket_protocol_send_payload(wsc, message, length, opcode, true); |
| 27 | } |
| 28 | |
| 29 | // Called before sending a close frame to the client |
| 30 | void echo_on_close(struct websocket_server_client *wsc, WEBSOCKET_CLOSE_CODE code, const char *reason) { |
| 31 | if (!wsc) return; |
| 32 | |
| 33 | websocket_debug(wsc, "Echo protocol client closing with code %d (%s): %s", |
| 34 | code, |
| 35 | code == WS_CLOSE_NORMAL ? "Normal" : |
| 36 | code == WS_CLOSE_GOING_AWAY ? "Going Away" : |
| 37 | code == WS_CLOSE_PROTOCOL_ERROR ? "Protocol Error" : |
| 38 | code == WS_CLOSE_INTERNAL_ERROR ? "Internal Error" : "Other", |
| 39 | reason ? reason : "No reason provided"); |
| 40 | |
| 41 | // Optional: Send a goodbye message |
| 42 | // websocket_protocol_send_text(wsc, "Goodbye from Netdata Echo WebSocket Server"); |
| 43 | } |
| 44 | |
| 45 | // Called when a client is about to be disconnected |
| 46 | void echo_on_disconnect(struct websocket_server_client *wsc) { |
| 47 | if (!wsc) return; |
| 48 | |
| 49 | websocket_debug(wsc, "Echo protocol client disconnected"); |
| 50 | |
| 51 | // No cleanup needed for the Echo protocol since it doesn't maintain any state |
| 52 | } |
| 53 | |
| 54 | // Initialize the Echo protocol |
| 55 | void websocket_echo_initialize(void) { |
| 56 | netdata_log_info("Echo protocol initialized"); |
| 57 | } |