Ensure only one web socket connection is enstablished

This commit is contained in:
Jannis Mattheis 2018-04-03 18:44:25 +02:00 committed by Jannis Mattheis
parent de35294263
commit c35df51634
1 changed files with 14 additions and 5 deletions

View File

@ -34,23 +34,32 @@ export function deleteMessage(id) {
axios.delete(config.get('url') + 'message/' + id).then(fetchMessages).then(() => snack('Message deleted')); axios.delete(config.get('url') + 'message/' + id).then(fetchMessages).then(() => snack('Message deleted'));
} }
let wsActive = false;
/** /**
* Starts listening to the stream for new messages. * Starts listening to the stream for new messages.
*/ */
export function listenToWebSocket() { export function listenToWebSocket() {
if (!getToken()) { if (!getToken() || wsActive) {
return; return;
} }
wsActive = true;
const wsUrl = config.get('url').replace('http', 'ws').replace('https', 'wss'); const wsUrl = config.get('url').replace('http', 'ws').replace('https', 'wss');
const ws = new WebSocket(wsUrl + 'stream?token=' + getToken()); const ws = new WebSocket(wsUrl + 'stream?token=' + getToken());
ws.onerror = (e) => { ws.onerror = (e) => {
console.log('WebSocket connection errored; trying again in 60 seconds', e); wsActive = false;
snack('Could not connect to the web socket, trying again in 60 seconds.'); console.log('WebSocket connection errored', e);
setTimeout(listenToWebSocket, 60000);
}; };
ws.onmessage = (data) => dispatcher.dispatch({type: 'ONE_MESSAGE', payload: JSON.parse(data.data)}); ws.onmessage = (data) => dispatcher.dispatch({type: 'ONE_MESSAGE', payload: JSON.parse(data.data)});
ws.onclose = () => UserAction.tryAuthenticate().then(listenToWebSocket); ws.onclose = () => {
wsActive = false;
UserAction.tryAuthenticate().then(() => {
snack('WebSocket connection closed, trying again in 30 seconds.');
setTimeout(listenToWebSocket, 30000);
});
};
} }