export default class WebSockBase {
|
webSock: WebSocket | null;
|
|
public set onOpen(fnc: () => void) {
|
this.webSock!.onopen = fnc;
|
}
|
|
public set onError(fnc: () => void) {
|
this.webSock!.onerror = fnc;
|
}
|
|
public set onMessage(fnc: (value: any) => void) {
|
this.webSock!.onmessage = fnc;
|
}
|
|
public set onClose(fnc: () => void) {
|
this.webSock!.onclose = fnc;
|
}
|
|
constructor() {
|
this.webSock = null;
|
}
|
/**
|
* 创建连接
|
* @param url
|
*/
|
createdWebSock(url: string) {
|
this.webSock = new WebSocket(`ws://${url}`);
|
this.webSock.onopen = (ev: Event) => {
|
console.log("websock--连接成功");
|
};
|
this.webSock.onclose = (ev: Event) => {
|
console.log("websock--连接关闭");
|
};
|
this.webSock.onerror = (ev: Event) => {
|
console.log("websock--连接失败");
|
};
|
}
|
|
/**
|
* 判断连接是否在线
|
*/
|
public isConnect = () => {
|
return this.webSock && this.webSock.readyState == WebSocket.OPEN;
|
};
|
|
/**
|
* 关闭连接
|
*/
|
public offConcat = () => {
|
return new Promise<void>((resolve, reject) => {
|
if (this.webSock) {
|
this.webSock.close();
|
this.webSock = null;
|
resolve();
|
} else {
|
reject();
|
}
|
});
|
};
|
}
|