26 lines
893 B
JavaScript
26 lines
893 B
JavaScript
mergeInto(LibraryManager.library, {
|
|
WSInit: function(urlPtr) {
|
|
const url = UTF8ToString(urlPtr);
|
|
window._ws = new WebSocket(url);
|
|
window._ws._queue = [];
|
|
window._ws.onopen = () => {
|
|
console.log("[WS] open, flushing", window._ws._queue.length);
|
|
window._ws._queue.forEach(m => window._ws.send(m));
|
|
window._ws._queue = [];
|
|
};
|
|
window._ws.onerror = e => console.error("[WS] error", e);
|
|
window._ws.onclose = () => console.warn("[WS] closed");
|
|
},
|
|
WSSend: function(jsonPtr) {
|
|
if (!window._ws) { console.error("[WS] not init"); return; }
|
|
const msg = UTF8ToString(jsonPtr);
|
|
if (window._ws.readyState === WebSocket.CONNECTING) {
|
|
window._ws._queue.push(msg);
|
|
} else if (window._ws.readyState === WebSocket.OPEN) {
|
|
window._ws.send(msg);
|
|
} else {
|
|
console.error("[WS] bad state", window._ws.readyState);
|
|
}
|
|
}
|
|
});
|