WebSocket client lifecycle
A browser WebSocket is an object with four events. onopen when the connection is established. onmessage for each frame the server sends. onclose when the connection ends. onerror when something goes wrong. Wire those four handlers and you have a working client.
export function connect(token: string, onEvent: (data: any) => void) {
const ws = new WebSocket('ws://localhost:3000?token=' + token);
ws.onopen = () => {
console.log('connected');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
onEvent(data);
};
ws.onclose = () => {
console.log('disconnected');
};
ws.onerror = (err) => {
console.error('ws error', err);
};
return ws;
}The simplest useful WebSocket client.
Quiz: Quiz
Loading practice…