What Is Best Practice To Websocket Reconnect In React?
I have react app with ticket polling (ticket is part of link for websocket connection). Then I pass websocket object to another component, because only this (another) component sho
Solution 1:
Wrap WebSocket connection and onmessage in a function. check if WebSocket is close, callback the function. Also may use setTimeout. Example :
functionconnect(){
//WebSocket Connection//WebSocket onmessage
}
conn.onclose = evt => {
console.log('Socket is closed.Reconnect will be attempted in 10 second.', evt.reason);
setTimeout(() =>connect(), 10000);
};
Solution 2:
I'm using this way
functionconnect() {
var ws = newWebSocket('ws://localhost:8080');
ws.onopen = function() {
// subscribe to some channels
ws.send(JSON.stringify({
//.... some message the I must send when I connect ....
}));
};
ws.onmessage = function(e) {
console.log('Message:', e.data);
};
ws.onclose = function(e) {
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
connect();
}, 1000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
}
connect();
Post a Comment for "What Is Best Practice To Websocket Reconnect In React?"