yao-node-client
Version:
A node client for yao application development
78 lines • 2.12 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocket = void 0;
const ws_1 = __importDefault(require("ws"));
const request_1 = __importDefault(require("./request"));
/**
* 模拟ws客户端。
*
* https://github.com/websockets/ws
*/
class WebSocket {
url;
protocols;
client;
ready;
messages;
/**
*
* @param url ws服务地址
* @param protocols 协议
*/
constructor(url, protocols) {
this.url = url;
this.protocols = protocols;
this.messages = [];
this.client = new ws_1.default(this.url, [protocols]);
let ref = this;
this.client.on("open", function open() {
ref.ready = true;
for (let index = 0; index < ref.messages.length; index++) {
let obj = ref.messages.shift();
ref.push(obj);
}
});
this.client.on("error", () => {
throw Error("连接异常");
});
this.client.on("message", function message(data) {
console.log("received: %s", data);
});
}
/**
*发送数据
* @param params 参数
*/
push(params) {
if (!this.ready) {
this.messages.push(params);
}
else {
this.client.send(params);
}
}
}
exports.WebSocket = WebSocket;
//另外一个可选项,使用远程调用的yao的push方法
class WebSocketYao {
url;
protocols;
constructor(url, protocols) {
this.url = url;
this.protocols = protocols;
}
push(message) {
const payload = {
type: "WebSocket",
method: "push",
url: this.url,
protocols: this.protocols,
message: message,
};
return (0, request_1.default)(payload);
}
}
//# sourceMappingURL=websocket.js.map