How to have mongoose managing multiple websocket URL

935 Views Asked by At

I have the websocket examples for Mongoose 6.12 running well on my embedded platform.

What I am wondering is how is it possible to manage multiple URL of websockets?

Our goal is to have multiple web pages on our platform, each one periodically retrieving data over websockets from the server. Depending on the websocket URL, different set of data would be returned.

Using the example "websocket_chat" as a reference, the sending of code :

for (c = mg_next(nc->mgr, NULL); c != NULL; c = mg_next(nc->mgr, c)) {
    if (c == nc) continue;
    mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, buf, strlen(buf));
}

would ideally filter out the URL that are not related to the URL being serviced:

for (c = mg_next(nc->mgr, NULL); c != NULL; c = mg_next(nc->mgr, c)) {
    if ((c == nc) **|| (strcmp(c->uri, "/ws/page1") == 0)**) continue;
    mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, buf, strlen(buf));
}

But it seems that the connection doesn't hold the URL associated to the connection.

This code is called periodically by the web server, not based on an Mongoose event.

Do you have any suggestions on how to achieve this?

Many thanks.

Fred.

1

There are 1 best solutions below

1
On BEST ANSWER

I think you can catch MG_EV_WEBSOCKET_HANDSHAKE_REQUEST event, which has access to the URI, and which can set the marker in the user_data:

static void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  switch (ev) {
    case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: {
      struct http_message *hm = (struct http_message *) ev_data;
      c->user_data = "foo";
      if (mg_vcmp(&hm->uri, "/uri1") == 0) c->user_data = "bar";
      break;
    }

Then in the broadcast handler, check the value of that marker.

for (c = mg_next(nc->mgr, NULL); c != NULL; c = mg_next(nc->mgr, c)) {
  if (c == nc) continue; /* Don't send to the sender. */
  if (c->user_data && strcmp(c->user_data, "bar") == 0)       
    mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, buf, strlen(buf));
  }
}