@parkersoftware/whoson-lib
Version:
Useful whoson related library
81 lines (80 loc) • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventDrivenSocket = void 0;
var EventDrivenSocket = /** @class */ (function () {
/**
* @constructor
* @param {Hooks} hooks - pass a hooks instance
*/
function EventDrivenSocket(hooks) {
var _this = this;
var self = this;
throwIf(isNull(hooks), "You need to pass hooks");
this._worker = new SharedWorker("SharedWorker.ts", "WhosOn Websocket Worker");
this._hooks = hooks;
var serverAddress = "";
if (isNull(window)) {
serverAddress = "localhost";
}
else {
serverAddress = window.location.hostname;
}
this._worker.port.onmessage = function (event) {
switch (event.data[0]) {
case "socket.opened":
_this._connected = true;
break;
case "socket.closed":
_this._connected = false;
break;
case "socket.message":
break;
}
self._hooks.call(event.data[0], event.data[1]);
};
this._address = "ws://" + serverAddress + ":8013";
this._connected = false;
}
Object.defineProperty(EventDrivenSocket.prototype, "connected", {
get: function () {
return this._connected;
},
enumerable: false,
configurable: true
});
/**
* connect to a web socket address
* @param address web socket address to connect to
*/
EventDrivenSocket.prototype.connect = function (address) {
var self = this;
if (isNotNull(address)) {
throwIf(address.startsWith("ws") === false, "Must be a websocket address");
}
var addressToConnectTo = address || this._address;
this._worker.port.postMessage(["socket.connect", addressToConnectTo]);
};
/**
* send a command
* @param cmdName the command name
* @param params any args you want to send along with the command
*/
EventDrivenSocket.prototype.send = function (cmdName, params) {
if (params === void 0) { params = null; }
var self = this;
var msg = {
"Command": "" + cmdName,
"Parameters": params
};
this._worker.port.postMessage(["socket.send", JSON.stringify(msg)]);
};
/**
* close the socket
*/
EventDrivenSocket.prototype.close = function () {
this._worker.port.postMessage(["socket.close"]);
};
return EventDrivenSocket;
}());
exports.EventDrivenSocket = EventDrivenSocket;
module.exports.EventDrivenSocket = EventDrivenSocket;