Created
April 11, 2021 06:40
-
-
Save smashah/8987a5f621be331e19db301643edb756 to your computer and use it in GitHub Desktop.
Socket client fallback URL implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 => { | |
... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could also update the
uri
attribute of the manager (so you don't have to transfer the event handlers):Source: https://github.com/socketio/socket.io-client/blob/7e81e66b2fb362fdff7caef0e417caf97109f0f6/lib/manager.ts#L498-L499