2019-07-30 09:05:41 -05:00
|
|
|
import { loadAdapter } from '../Adapters/AdapterLoader';
|
|
|
|
|
import { WSAdapter } from '../Adapters/WebSocketServer/WSAdapter';
|
2016-08-12 13:25:24 -04:00
|
|
|
import logger from '../logger';
|
2019-07-30 09:05:41 -05:00
|
|
|
import events from 'events';
|
2016-03-10 14:27:00 -08:00
|
|
|
|
|
|
|
|
export class ParseWebSocketServer {
|
|
|
|
|
server: Object;
|
|
|
|
|
|
2018-09-01 13:58:06 -04:00
|
|
|
constructor(
|
|
|
|
|
server: any,
|
|
|
|
|
onConnect: Function,
|
2019-07-30 09:05:41 -05:00
|
|
|
config
|
2018-09-01 13:58:06 -04:00
|
|
|
) {
|
2019-07-30 09:05:41 -05:00
|
|
|
config.server = server;
|
|
|
|
|
const wss = loadAdapter(
|
|
|
|
|
config.wssAdapter,
|
|
|
|
|
WSAdapter,
|
|
|
|
|
config,
|
|
|
|
|
);
|
|
|
|
|
wss.onListen = () => {
|
2016-08-12 13:25:24 -04:00
|
|
|
logger.info('Parse LiveQuery Server starts running');
|
2019-07-30 09:05:41 -05:00
|
|
|
};
|
|
|
|
|
wss.onConnection = (ws) => {
|
2016-03-10 14:27:00 -08:00
|
|
|
onConnect(new ParseWebSocket(ws));
|
|
|
|
|
// Send ping to client periodically
|
2016-12-07 15:17:05 -08:00
|
|
|
const pingIntervalId = setInterval(() => {
|
2016-03-10 14:27:00 -08:00
|
|
|
if (ws.readyState == ws.OPEN) {
|
|
|
|
|
ws.ping();
|
|
|
|
|
} else {
|
|
|
|
|
clearInterval(pingIntervalId);
|
|
|
|
|
}
|
2019-07-30 09:05:41 -05:00
|
|
|
}, config.websocketTimeout || 10 * 1000);
|
|
|
|
|
};
|
|
|
|
|
wss.start();
|
2016-03-10 14:27:00 -08:00
|
|
|
this.server = wss;
|
|
|
|
|
}
|
2019-07-30 09:05:41 -05:00
|
|
|
|
|
|
|
|
close() {
|
|
|
|
|
if (this.server && this.server.close) {
|
|
|
|
|
this.server.close();
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-03-10 14:27:00 -08:00
|
|
|
}
|
|
|
|
|
|
2019-07-30 09:05:41 -05:00
|
|
|
export class ParseWebSocket extends events.EventEmitter {
|
2016-03-10 14:27:00 -08:00
|
|
|
ws: any;
|
|
|
|
|
|
|
|
|
|
constructor(ws: any) {
|
2019-07-30 09:05:41 -05:00
|
|
|
super();
|
|
|
|
|
ws.onmessage = (request) => this.emit('message', request);
|
|
|
|
|
ws.onclose = () => this.emit('disconnect');
|
2016-03-10 14:27:00 -08:00
|
|
|
this.ws = ws;
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-24 15:47:41 -05:00
|
|
|
send(message: any): void {
|
2016-03-10 14:27:00 -08:00
|
|
|
this.ws.send(message);
|
|
|
|
|
}
|
|
|
|
|
}
|