Skip to content

Instantly share code, notes, and snippets.

@Yummy-Yums
Last active February 29, 2024 12:58
Show Gist options
  • Save Yummy-Yums/80de6b225ec993c718cdc94db3be93a0 to your computer and use it in GitHub Desktop.
Save Yummy-Yums/80de6b225ec993c718cdc94db3be93a0 to your computer and use it in GitHub Desktop.
Reflex Cxn Issue
var wsUri = "wss://ws.postman-echo.com/raw";
var log;
var websocket;
var inactivityTimeout;
function init(){
log = document.getElementById("log");
testWebSocket();
}
function testWebSocket(){
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onerror = function(evt) { onError(evt) };
inactivityTimeout = setTimeout(() => {
console.log('WebSocket connection closed due to inactivity.');
websocket.close();
}, 5000);
}
function onOpen(evt){
writeLog("CONNECTED");
sendMessage("Hello world");
}
function onClose(evt){
writeLog("WebSocket DISCONNECTED");
}
function onMessage(evt){
writeLog('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
console.log('Received message:', event.data);
clearTimeout(inactivityTimeout);
inactivityTimeout = setTimeout(() => {
console.log('WebSocket connection closed due to inactivity.');
websocket.close();
}, 5000); // Reset timeout (5 minutes)
}
function onError(evt){
writeLog('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function sendMessage(message){
writeLog("SENT: " + message);
websocket.send(message);
}
function writeLog(message){
var pre = document.createElement("p");
pre.innerHTML = message;
log.appendChild(pre);
}
window.addEventListener("load", init, false);
document.addEventListener('visibilitychange', function() {
// Check if the tab is now active
if (document.visibilityState === 'visible') {
if (websocket.readyState !== WebSocket.OPEN) {
console.log("Socket was closed, reconnecting");
testWebSocket();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment