AnP/Public/ecma/Drivers/WebSocketsDriver.ecma.js
2026-05-28 07:24:34 +02:00

131 lines
3.0 KiB
JavaScript

"use strict";
import {Common} from "../Utils/Common.ecma.js";
import {Event} from "../Application/Event.ecma.js";
/**
* @class WebSocketsDriver
* @constructor
* @param {!(Object.<string, any|null>|Array.<any|null>)} inputs
* @returns {void}
* @access public
* @static
*/
export const WebSocketsDriver = (function(){
/**
* @callback continue_callback
* @param {boolean} ok
* @return {void}
*/
/**
* @constructs WebSocketsDriver
* @param {!(Object.<string, any|null>|Array.<any|null>)} inputs
* @returns {void}
* @access private
* @static
*/
const WebSocketsDriver = function(inputs){
/** @type {WebSocketsDriver} */
const self = this;
/** @type {WebSocket|null} */
let client = null,
/** @type {string|null} */
url = null,
/** @type {boolean} */
started = false;
/** @type {Event} */
this.on_open = new Event();
/** @type {Event} */
this.on_message = new Event();
/** @type {Event} */
this.on_error = new Event();
/** @type {Event} */
this.on_close = new Event();
/**
* @returns {void}
* @access private
*/
const constructor = () => {
url = Common.get_string(inputs.url, "ws://localhost:8080");
};
/**
* @param {?continue_callback} callback
* @returns {boolean}
* @access public
*/
this.start = (callback = null) => {
/** @type {continue_callback} */
const end = ok => Common.execute(callback, ok);
if(started){
end(false);
return false;
};
started = true;
client = new WebSocket(url);
client.onopen = on_open;
client.onmessage = on_message
client.onerror = on_error;
client.onclose = on_close;
return true;
};
/**
* @param {?continue_callback} callback
* @returns {boolean}
* @access public
*/
this.close = (callback = null) => {
/** @type {continue_callback} */
const end = ok => Common.execute(callback, ok);
if(!started){
end(false);
return false;
};
started = false;
client.close();
client = null;
return true;
};
const on_open = event => {
console.log(["client", event]);
};
const on_message = event => {
console.log(["message", event]);
};
const on_error = event => {
console.log(["error", event]);
};
const on_close = event => {
console.log(["close", event]);
};
this.send = message => {
client.send(message);
};
constructor();
};
return WebSocketsDriver;
})();