rui_orig/app_socket.js

79 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-01-15 16:13:46 +03:00
let socket
2022-10-27 16:14:30 +03:00
function sendMessage(message) {
if (!socket) {
createSocket(function() {
sendMessage( "reconnect{session=" + sessionID + "}" );
if (!windowFocus) {
windowFocus = true;
sendMessage( "session-resume{session=" + sessionID +"}" );
}
socket.send(message);
});
} else {
socket.send(message);
2022-10-27 16:14:30 +03:00
}
}
function createSocket(onopen) {
let socketUrl = document.location.protocol == "https:" ? "wss://" : "ws://"
2022-10-27 16:14:30 +03:00
socketUrl += document.location.hostname
2024-01-15 16:13:46 +03:00
const port = document.location.port
2022-10-27 16:14:30 +03:00
if (port) {
socketUrl += ":" + port
}
socketUrl += window.location.pathname + "ws"
socket = new WebSocket(socketUrl);
socket.onopen = onopen;
socket.onclose = onSocketClose;
socket.onerror = onSocketError;
2022-10-27 16:14:30 +03:00
socket.onmessage = function(event) {
window.execScript ? window.execScript(event.data) : window.eval(event.data);
};
}
function closeSocket() {
if (socket) {
socket.close()
}
}
2022-10-27 16:14:30 +03:00
window.onload = createSocket(function() {
2022-11-01 20:13:09 +03:00
sendMessage( sessionInfo() );
});
window.onfocus = function() {
windowFocus = true
if (!socket) {
createSocket(function() {
sendMessage( "reconnect{session=" + sessionID + "}" );
sendMessage( "session-resume{session=" + sessionID +"}" );
});
} else {
sendMessage( "session-resume{session=" + sessionID +"}" );
}
2022-10-27 16:14:30 +03:00
}
function onSocketReopen() {
2022-10-27 16:14:30 +03:00
sendMessage( "reconnect{session=" + sessionID + "}" );
}
function socketReconnect() {
if (!socket) {
createSocket(onSocketReopen);
2022-10-27 16:14:30 +03:00
}
}
function onSocketClose(event) {
2022-10-27 16:14:30 +03:00
console.log("socket closed")
socket = null;
if (!event.wasClean && windowFocus) {
window.setTimeout(socketReconnect, 10000);
}
}
function onSocketError(error) {
2022-10-27 16:14:30 +03:00
console.log(error);
}