]>
git.r.bdr.sh - rbdr/forum/blob - src/socket_coordinator.js
1 import EventEmitter
from 'eventemitter3';
2 import { socketServer
} from './config/config';
6 kReconnectInterval: 3000, // How often we attempt to reconnect
8 eventEmitter: new EventEmitter(), // internal event emitter
9 socket: null, // stores the socket connection
10 retry: null, // stores the retry operation
14 console
.debug('Connecting socket.');
15 internals
.socket
= new WebSocket(socketServer
);
17 internals
.socket
.addEventListener('message', internals
.onMessage
);
18 internals
.socket
.addEventListener('error', internals
.onError
);
19 internals
.socket
.addEventListener('close', internals
.onClose
);
22 // Handles socket errors.
26 console
.error('Socket error. Closing connection');
27 internals
.socket
.close();
30 // Handles socket errors.
34 console
.debug(`Connection closed: ${event.reason || 'Unknown reason'}. Retrying in ${internals.kReconnectInterval}ms`);
36 internals
.retry
&& clearTimeout(internals
.retry
);
37 internals
.retry
= setTimeout(() => {
39 console
.debug('Reconnecting socket.');
40 internals
.retry
= null;
42 }, internals
.kReconnectInterval
);
45 // Forwards events from the socket to our internal event emitter.
49 internals
.eventEmitter
.emit('message', event
);
53 export const onMessage = function (listener
) {
55 if (!internals
.socket
) {
59 internals
.eventEmitter
.on('message', (message
) => {
61 listener(JSON
.parse(message
.data
));