ws_close - send CLOSE control-frame

void ws_close(struct websockets *ws, const enum ws_close_reason code, const char reason[], const size_t len)

Thread-safe way to stop websockets connection.

This will activate a internal WS_USER_CMD_EXIT flag that will force disconnect when the next iteration begins.

Note

it will create a copy of the reason string

Parameters
  • ws – the WebSockets handle created with ws_init()

  • code – the WebSockets CLOSE opcode

  • reason – the close reason

  • len – the reason length

Example

void on_connect(void *data,
                struct websockets *ws,
                struct ws_info *info,
                const char *ws_protocols)
{
  char reason[] = "Sorry to bother!";

  ws_close(ws, WS_CLOSE_REASON_NORMAL, reason, sizeof(reason));
}

int main(void)
{
  struct ws_callbacks cbs = { .on_connect = &on_connect };
  CURLM *mhandle = curl_multi_init();
  struct websockets *ws = ws_init(&cbs, mhandle, NULL);
  ws_set_url(ws, "wss://example.com", NULL);

  /* run the event-loop */
  ws_start(ws);

  uint64_t tstamp;
  bool is_running;
  do {
    is_running = ws_easy_run(ws, 5, &tstamp);
  } while (is_running);

  ws_end(ws);

  ws_cleanup(ws);
  curl_multi_cleanup(mhandle);
}