Skip to content

Instantly share code, notes, and snippets.

@uinz
Last active March 26, 2018 15:23
Show Gist options
  • Select an option

  • Save uinz/b4767573f479755085b6bb881dc4d370 to your computer and use it in GitHub Desktop.

Select an option

Save uinz/b4767573f479755085b6bb881dc4d370 to your computer and use it in GitHub Desktop.
reconnect ws
import { EventEmitter } from 'events';
import * as SocksProxyAgent from 'socks-proxy-agent';
import * as WebSocket from 'ws';
export class WS extends EventEmitter {
private instance?: WebSocket;
constructor(
private url: string,
private proxy?: string
) {
super();
}
public open = () => {
if (this.proxy) {
const agent = new SocksProxyAgent(this.proxy); // socks://host:port
this.instance = new WebSocket(this.url, { agent });
} else {
this.instance = new WebSocket(this.url);
}
this.instance.on('open', () => {
this.emit('open');
});
this.instance.on('message', (data) => {
this.emit('message', data);
});
this.instance.on('close', (code) => {
if (code === 1000) {
console.log('WebSocket: closed');
this.emit('close', code);
} else {
this.reconnect();
}
});
this.instance.on('ping', (data) => {
this.emit('ping', data);
});
this.instance.on('pong', (data) => {
this.emit('pong', data);
});
this.instance.on('error', (error) => {
this.emit('error', error);
});
}
private reconnect = () => {
console.log(`reconnect: ${this.url}`);
if (this.instance) {
this.instance.removeAllListeners();
}
setTimeout(this.open, 1000);
}
public send = (data: any, stringify = true) => {
if (this.instance) {
if (stringify) {
this.instance.send(JSON.stringify(data));
} else {
this.instance.send(data);
}
} else {
throw Error('WebSocket not open!');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment