// Sunucuya WebSocket bağlantısı; koparsa otomatik yeniden bağlanır.
export function connectServer(onMessage, onState = () => {}) {
let ws = null;
let closed = false;
const queue = [];
function open() {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
ws = new WebSocket(`${proto}://${location.host}/ws`);
ws.onopen = () => {
onState(true);
while (queue.length) ws.send(queue.shift());
};
ws.onmessage = (e) => {
try {
onMessage(JSON.parse(e.data));
} catch (err) {
console.error(err);
}
};
ws.onclose = () => {
onState(false);
if (!closed) setTimeout(open, 1500);
};
}
open();
return {
send(obj) {
const s = JSON.stringify(obj);
if (ws?.readyState === 1) ws.send(s);
else queue.push(s);
},
close() {
closed = true;
ws?.close();
},
};
}
Lisans bilgisi projenin LICENSE dosyasında.