Skip to content

Instantly share code, notes, and snippets.

@ywwwtseng
Last active June 15, 2023 21:06
Show Gist options
  • Save ywwwtseng/f35323079468ff64189db1b454ba4f5d to your computer and use it in GitHub Desktop.
Save ywwwtseng/f35323079468ff64189db1b454ba4f5d to your computer and use it in GitHub Desktop.
websocket
class Socket {
constructor(
domain,
{ reconnection = true, reconnectionDelay = 1000 } = {
reconnection: true,
reconnectionDelay: 1000,
}
) {
this.ws = this.connect(domain);
this.reconnection = reconnection;
this.reconnectionDelay = reconnectionDelay;
this.CLOSED = true;
this.events = {};
}
connect(domain) {
if (!domain) return null;
this.ws = new WebSocket(domain);
this.CLOSED = false;
this.ws.onopen = () => {
if (this.events.open) this.events.open();
// subscribe to some channels
this.ws.send(JSON.stringify({
//.... some message the I must send when I connect ....
}));
};
this.ws.onmessage = (e) => {
const type = e.data && e.data.type;
const data = e.data && e.data.data;
if (this.events[type]) this.events[type](JSON.parse(data));
};
this.ws.onclose = (e) => {
console.log('Socket is closed. Reconnect will be attempted.', e.reason);
if (this.reconnection && !this.CLOSED) {
setTimeout(() => {
this.ws = this.connect(domain);
}, this.reconnectionDelay);
}
};
this.ws.onerror = (err) => {
console.error(
'Socket encountered error: ',
err.message,
'Closing socket'
);
this.ws.close();
};
return this.ws;
}
disconnect() {
this.CLOSED = true;
this.ws.close();
}
on(eventName, handler) {
this.events[eventName] = handler;
}
emit(eventName, data) {
this.ws.send(
JSON.stringify({
type: eventName,
data,
})
);
}
}
const ws = new Socket(domain, options);
// Emits an event to the socket identified by the string name.
// ws.emit('hello', 'world');
// Register a new handler for the given event.
// ws.on('news', (data) => { console.log(data); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment