How to use the close function from ws

Find comprehensive JavaScript ws.close code examples handpicked from public code repositorys.

ws.close is a function provided by the ws module in Node.js that closes the WebSocket instance.

94
95
96
97
98
99
100
101
102
103
    params[key] = value;
  }
}

if (!Object.keys(params).includes(RTSP_URL_KEY)) {
  ws.close();
  return
}

let rtspUrl = params.url;
fork icon0
star icon0
watch icon1

97
98
99
100
101
102
103
104
105
106
ws.on('message', onMessage);
ws.on('close', onClose);
ws.on('error', onError);
if (location.pathname !== '/ws/chat') {
    // close ws:
    ws.close(4000, 'Invalid URL');
}
// check user:
let user = parseUser(ws.upgradeReq);
if (!user) {
fork icon0
star icon0
watch icon0

How does ws.close work?

ws.close is a method provided by the Node.js WebSocket library ws that allows a WebSocket server or client to close an active WebSocket connection. When invoked, the ws.close method sends a close frame to the other endpoint of the WebSocket connection, indicating that the connection should be closed. The other endpoint may respond with its own close frame, which is passed to the onclose event handler of the WebSocket object. The ws.close method takes two optional arguments: code and reason. The code argument is a numeric code indicating the reason for closing the connection, and the reason argument is a string providing further details about the reason for closing. If provided, these arguments will be sent to the other endpoint of the WebSocket connection in the close frame.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const WebSocket = require("ws");

const ws = new WebSocket("ws://localhost:8080");

ws.on("open", function () {
  console.log("Connected to WebSocket server");

  // Close the WebSocket connection after 5 seconds
  setTimeout(function () {
    ws.close();
  }, 5000);
});

ws.on("close", function () {
  console.log("Disconnected from WebSocket server");
});

In this example, we create a new WebSocket connection to a server running on localhost at port 8080. Once the connection is established, we set a timeout of 5 seconds using setTimeout(). After the timeout elapses, we call the close() method on the WebSocket object to gracefully close the connection. Finally, we handle the close event to log a message to the console when the connection is closed.