cloud-game/web/js/network/socket.js
Sergey Stepanov 2bc64a3be8 Migrate from IIFE to modern ES modules
These modules should be supported by all contemporary browsers, and this transition should resolve most issues related to the explicit import order of the .js files.
2024-03-17 22:09:43 +03:00

51 lines
1.2 KiB
JavaScript

import {
pub,
MESSAGE
} from 'event';
import {log} from 'log';
let conn;
const buildUrl = (params = {}) => {
const url = new URL(window.location);
url.protocol = location.protocol !== 'https:' ? 'ws' : 'wss';
url.pathname = "/ws";
Object.keys(params).forEach(k => {
if (!!params[k]) url.searchParams.set(k, params[k])
})
return url
}
const init = (roomId, wid, zone) => {
let objParams = {room_id: roomId, zone: zone};
if (wid) objParams.wid = wid;
const url = buildUrl(objParams)
console.info(`[ws] connecting to ${url}`);
conn = new WebSocket(url.toString());
conn.onopen = () => {
log.info('[ws] <- open connection');
};
conn.onerror = () => log.error('[ws] some error!');
conn.onclose = (event) => log.info(`[ws] closed (${event.code})`);
conn.onmessage = response => {
const data = JSON.parse(response.data);
log.debug('[ws] <- ', data);
pub(MESSAGE, data);
};
};
const send = (data) => {
if (conn.readyState === 1) {
conn.send(JSON.stringify(data));
}
}
/**
* WebSocket connection module.
*
* Needs init() call.
*/
export const socket = {
init,
send
}