Websocket

struct mg_ws_message

struct mg_ws_message {
  struct mg_str data; // WebSocket message data
  uint8_t flags;      // WebSocket message flags
};

This structure represents the WebSocket message, the flags element corresponds to the first byte as described in RFC 6455 section 5.2.

To extract the message type from an incoming message, check the four LSBs in the flags element of the struct mg_ws_message.

Possible WebSocket message types:

#define WEBSOCKET_OP_CONTINUE 0
#define WEBSOCKET_OP_TEXT 1
#define WEBSOCKET_OP_BINARY 2
#define WEBSOCKET_OP_CLOSE 8
#define WEBSOCKET_OP_PING 9
#define WEBSOCKET_OP_PONG 10
// Mongoose events handler
void fn(struct mg_connection *c, int ev, void *ev_data) {
  if (ev == MG_EV_WS_MSG) {
    struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
    msgtype = wm->flags & 0x0F;
    if (msgtype == WEBSOCKET_OP_BINARY) {
      // This is a binary data message
    } else if (msgtype == WEBSOCKET_OP_TEXT) {
      // This is a text data message
    }
  }
}

To send a message, use the proper message type as described in RFC 6455 section 5.6 for data frames. when calling mg_ws_send() or mg_ws_printf() below

mg_ws_connect()

struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
                                    mg_event_handler_t fn, void *fn_data,
                                    const char *fmt, ...);

Create a client WebSocket connection.

Parameters:

  • mgr - Event manager to use
  • url - Specifies remote URL, e.g. http://google.com. If this URL is 'wss', the is_tls flag will be set
  • fn - An event handler function
  • fn_data - an arbitrary pointer, which will be stored in the connection structure as c->fn_data, so the event handler can use it when called.
  • fmt - format string in printf semantics for additional HTTP headers, or NULL. See mg_snprintf for the list of supported format specifiers

Return value: created connection, or NULL on error. Possible errors are: not enough memory, a NULL URL, or, in the case of our built-in TCP/IP stack, the network not being ready.

Note: This function does not connect to the requested peer, it allocates required resources and starts the connection process. Once our peer is really connected, an MG_EV_CONNECT event is sent to the connection event handler.

Usage example:

struct mg_connection *c = mg_ws_connect(&mgr, "ws://test_ws_server.com:1000",
                                        handler, NULL, "%s", "Sec-WebSocket-Protocol: echo\r\n");
if(c == NULL) fatal("Cannot create connection");

mg_ws_upgrade()

void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *,
                   const char *fmt, ...);

Upgrade given HTTP connection to WebSocket. Parameter fmt is a printf-like format string for the extra HTTP headers returned to the client in a WebSocket handshake. Set it to NULL if no extra headers need to be passed.

Parameters:

  • c - Connection to use
  • hm - HTTP message
  • fmt - format string in printf semantics for additional HTTP headers, or NULL. See mg_snprintf for the list of supported format specifiers

Return value: None

Usage example:

// Mongoose events handler
void fn(struct mg_connection *c, int ev, void *ev_data) {
  if (ev == MG_EV_HTTP_MSG) {
    struct mg_http_message *hm = (struct mg_http_message *) ev_data;
    mg_ws_upgrade(c, hm, NULL);  // Upgrade HTTP to WS
  }
}

mg_ws_send()

size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len, int op);

Send data to WebSocket peer

Parameters:

  • c - Connection to use
  • buf - Data to send
  • len - Data size
  • op - WebSocket message type, see WebSocket message type above

Return value: sent bytes count

Usage example:

// Mongoose events handler
void fn(struct mg_connection *c, int ev, void *ev_data) {
  if (ev == MG_EV_WS_OPEN) {
    struct mg_http_message *hm = (struct mg_http_message *) ev_data;
    mg_ws_send(c, "opened", 6, WEBSOCKET_OP_BINARY);  // Send "opened" to web socket connection
  }
}

mg_ws_printf(), mg_ws_vprintf()

size_t mg_ws_printf(struct mg_connection *, int op, const char *fmt, ...);
size_t mg_ws_vprintf(struct mg_connection *, int op, const char *fmt, va_list *);

Same as mg_ws_send(), but formats data using printf() semantics.

Parameters:

  • c - Connection to use
  • op - WebSocket message type, see WebSocket message type above
  • fmt - format string in printf semantics. See mg_snprintf for the list of supported format specifiers

Return value: sent bytes count

Usage example:

mg_ws_printf(c, WEBSOCKET_OP_TEXT, "Hello, %s!", "world");

mg_ws_wrap()

size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op)

Convert data in output buffer to WebSocket format. Useful when implementing a protocol over WebSocket See tutorials/mqtt/mqtt-over-ws-client for a full example.

Parameters:

  • c - Connection to use
  • len - Bytes count to convert
  • op - Websocket message type (see mg_ws_send)

Return value: New size of connection output buffer

Usage example:

size_t len = c->send.len;         // Store output buffer len
mg_mqtt_login(c, s_url, &opts);   // Write MQTT login message
mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY); // Wrap it into WS