Send a binary data example from server to client #1689
-
Hi everyone! I use server example from the master branch of the mongoose library (examples/websocket-server/main.c). All works fine, but I want to know, how to send integers as binary data to client for example? With WEBSOCKET_OP_BINARY flag. My dummy example:
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39) |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
Check the WebSocket server example and tutorial. |
Beta Was this translation helpful? Give feedback.
-
It is a bad idea to send native data types over the network. mg_ws_printf(c, "{%Q: %d}", "value", 123); // Sends a {"value": 123} websocket message On the receiving side, struct mg_ws_message *wm = ev_data;
long value = mg_json_get_long(wm->data, "$.value", -1); // value is 123 You can do a less verbose enconding - just send a number in a string form: |
Beta Was this translation helpful? Give feedback.
-
void *value = malloc(wm->data.len);
memcpy(value, wm->data.ptr, wm->data.len);
printf("value = %d\n",* (int*)value); That is an overkill. There is no need to copy the received data in order to parse it: int value = * (int *) wm->data.ptr; // Assumes that wm->data.len >= sizeof(int) |
Beta Was this translation helpful? Give feedback.
Check the WebSocket server example and tutorial.
Check the MQTT over WebSocket client example and tutorial; when sending binary protocols, you need to "wrap" your message (add "message boundaries") so the other end can identify it as a whole message