UNPKG

@cimo/websocket

Version:

Websocket (server/client). Light, fast and secure.

231 lines 8.54 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); const helperSrc = __importStar(require("../HelperSrc")); class Manager { ws; address; handleReceiveDataList; clientIdCurrent; callbackConnection; callbackDisconnection; handleReceiveData = (tag, data) => { for (const handleReceiveData of this.handleReceiveDataList) { if (handleReceiveData.tag === tag) { handleReceiveData.callback(data); break; } } }; handleReceiveDataRemove = (tag) => { for (let a = this.handleReceiveDataList.length - 1; a >= 0; a--) { if (this.handleReceiveDataList[a].tag === tag) { this.handleReceiveDataList.splice(a, 1); } } }; dataClientIdCurrent = () => { this.receiveData("clientId_current", (data) => { this.clientIdCurrent = data; }); }; create = () => { this.ws = new WebSocket(this.address); this.ws.binaryType = "arraybuffer"; this.dataClientIdCurrent(); this.ws.onopen = () => { helperSrc.writeLog("@cimo/websocket - Client - Manager.ts - create() - onopen()", "Connection open."); if (this.callbackConnection) { this.callbackConnection(); } }; let messageTagDownload = ""; this.ws.onmessage = (event) => { if (this.ws) { if (typeof event.data === "string") { const eventData = event.data; if (!eventData.trim()) { return; } if (!helperSrc.isJson(eventData)) { return; } const messageObject = JSON.parse(eventData); if (!messageObject || typeof messageObject.tag !== "string") { return; } if (messageObject.tag === "cws_download") { messageTagDownload = messageObject.tag; } this.handleReceiveData(messageObject.tag, messageObject.data); } else if (typeof event.data !== "string" && messageTagDownload) { const view = new DataView(event.data); this.handleReceiveData(messageTagDownload, view); messageTagDownload = ""; } } }; this.ws.onclose = () => { helperSrc.writeLog("@cimo/websocket - Client - Manager.ts - create() - onclose()", "Connection close."); this.ws = undefined; if (this.callbackDisconnection) { this.callbackDisconnection(); } }; }; constructor(addressValue) { this.ws = undefined; this.address = addressValue; this.handleReceiveDataList = []; this.clientIdCurrent = ""; this.callbackConnection = null; this.callbackDisconnection = null; } checkStatus = (mode, callback) => { if (mode === "connection") { this.callbackConnection = callback; } else if (mode === "disconnection") { this.callbackDisconnection = callback; } }; sendMessage = (mode, data, tag = "", timeout = 0) => { if (this.ws && this.ws.readyState === WebSocket.OPEN) { if (!(data instanceof ArrayBuffer) && !(typeof data === "string") && !(typeof data === "object" && data !== null)) { helperSrc.writeLog("@cimo/websocket - Client - Manager.ts - sendMessage()", "Invalid data type!"); } if (mode === "text" && !(data instanceof ArrayBuffer)) { let resultData = ""; if (typeof data === "string") { resultData = data; } else if (typeof data === "object") { resultData = JSON.stringify(data); } const messageObject = { tag: `cws_${tag}`, data: window.btoa(String.fromCharCode(...new TextEncoder().encode(resultData))) }; if (timeout > 0) { const timeoutEvent = setTimeout(() => { clearTimeout(timeoutEvent); if (this.ws) { this.ws.send(JSON.stringify(messageObject)); } }, timeout); } else { this.ws.send(JSON.stringify(messageObject)); } } else if (mode === "binary" && data instanceof ArrayBuffer) { this.ws.send(data); } else { helperSrc.writeLog("@cimo/websocket - Client - Manager.ts - sendMessage()", "Message type doesn't match mode!"); } } else { helperSrc.writeLog("@cimo/websocket - Client - Manager.ts - sendMessage()", "Client not connected!"); } }; sendDataBroadcast = (data) => { this.sendMessage("text", data, "broadcast"); }; sendDataUpload = (fileName, file) => { this.sendMessage("text", fileName, "upload"); this.sendMessage("binary", file, "", 100); }; sendDataDirect = (dataValue, clientId) => { if (clientId !== "") { const data = { time: new Date().toISOString(), content: dataValue, fromClientId: this.clientIdCurrent, toClientId: clientId }; this.sendMessage("text", data, "direct"); } }; receiveData = (tag, callbackValue) => { const cwsTag = `cws_${tag}`; this.handleReceiveDataRemove(cwsTag); this.handleReceiveDataList.push({ tag: cwsTag, callback: (data) => { let resultData; if (typeof data === "string") { const decoded = helperSrc.base64ToUtf8(data); resultData = !helperSrc.isJson(decoded) ? decoded : JSON.parse(decoded); } else { resultData = data; } callbackValue(resultData); } }); }; receiveDataDownload = (callback) => { let fileName = ""; this.receiveData("download", (data) => { if (typeof data === "string") { fileName = data; } else { callback(data, fileName); fileName = ""; } }); }; receiveDataDirect = (callback) => { this.receiveData("direct", (data) => { callback(data); }); }; open = () => { if (!this.ws) { this.create(); } }; close = () => { if (this.ws) { this.sendMessage("text", "", "disconnect"); this.ws.close(); } }; } exports.default = Manager; //# sourceMappingURL=Manager.js.map