Skip to content

Instantly share code, notes, and snippets.

@checklyalex
Created November 15, 2023 15:03
Show Gist options
  • Save checklyalex/d1be4b5ed8ff6d4a3dff8d6688373176 to your computer and use it in GitHub Desktop.
Save checklyalex/d1be4b5ed8ff6d4a3dff8d6688373176 to your computer and use it in GitHub Desktop.
Websocket Example
import WebSocket from 'ws';
const url = `wss://ws.postman-echo.com/raw`
const ws = new WebSocket(url);
const timeout = setTimeout(function () {
console.log('Failed to receive expected data within timeout. Terminating the WebSocket connection.')
ws.close()
throw new Error('Failed to receive expected data within timeout.')
}, 10000)
ws.on('error', console.error)
ws.on('message', function message(data) {
const jsonData = JSON.parse(data);
if (jsonData.type === "KEEP_ALIVE") {
console.log('Received keep alive')
} else if (jsonData.type === "CONN_ERROR") {
console.log('Received CONN_ERROR')
ws.close()
} else if (jsonData.type === "SUBACK") {
// The SUBACK message is sent in response to the SUB message from sendMessage()
// After receiving a SUBACK, we can end the check.
console.log('Received suback. Terminating the connection.')
// Close the connection
ws.close()
}
})
ws.on('close', function close() {
console.log('disconnected');
// Clear the timeout since the WebSocket connection has been closed.
clearTimeout(timeout)
})
async function sendMessage(id) {
const payload = `{
"action": "subscribe",
"channels": [
"channel1",
"channel2",
"channel3"
]
}`
ws.send(JSON.stringify(payload));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment