Skip to content

Instantly share code, notes, and snippets.

@smashah
Created April 11, 2021 06:40
Show Gist options
  • Save smashah/8987a5f621be331e19db301643edb756 to your computer and use it in GitHub Desktop.
Save smashah/8987a5f621be331e19db301643edb756 to your computer and use it in GitHub Desktop.
Socket client fallback URL implementation
//the url to try first
const socketUrl = `${window.location.origin}${window.location.pathname.split('/').filter(x=>!x.includes('.')).join('/')}`;
//the url to try next
const fallbackUrl = window.location.origin
//try with main socketUrl
let socket = io(socketUrl);
//how many times to attempt to reconnect socketUrl before falling back to fallbackUrl
socket.io.reconnectionAttempts(3)
//detect reconnect attempts
socket.io.on("reconnect_attempt", () => {
console.log("reconnect_attempt");
});
//detect when reconect attempts spent.
socket.io.on("reconnect_failed", () => {
console.log("reconnect_failed");
console.log('trying differnt URL, transferring all event listeners')
//make copy of all existing socket listeners
const callbacks = [
...Object.entries(socket._callbacks)
]
//change socket to fallbackUrl
socket = io(fallbackUrl);
//migrate all existing listeners
callbacks.map(([key, callbacks]) => callbacks.map(cb => socket.on(`${key.replace('$','')}`, cb)))
});
socket.on('connect', function() {
console.log('Connected to:', socket);
});
socket.on('disconnect', (reason) => {
...
socket.close();
});
socket.on('message', data => {
...
});
@darrachequesne
Copy link

You could also update the uri attribute of the manager (so you don't have to transfer the event handlers):

socket.io.on("reconnect_failed", () => {
  socket.io.uri = fallbackUrl;
});

Source: https://github.com/socketio/socket.io-client/blob/7e81e66b2fb362fdff7caef0e417caf97109f0f6/lib/manager.ts#L498-L499

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment