feat: ws工具新增连接状态函数

This commit is contained in:
TsMask
2024-02-28 17:37:09 +08:00
parent d52fdc115c
commit d7e08a1fff

View File

@@ -160,11 +160,15 @@ export class WS {
}
}
// 发送消息
public send(data: Record<string, any>) {
/**
* 发送消息
* @param data JSON数据
* @returns
*/
public send(data: Record<string, any>): boolean {
if (!this.ws) {
console.warn('websocket unavailable');
return;
return false;
}
// 非正常状态关闭
@@ -173,7 +177,7 @@ export class WS {
this.ws.readyState === WebSocket.CLOSING
) {
this.close();
return;
return false;
}
// 正在连接时
if (this.ws.readyState === WebSocket.CONNECTING) {
@@ -184,7 +188,21 @@ export class WS {
// 在连接的
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
return true;
}
return false;
}
/**连接状态
*
* WebSocket.OPEN
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)
*/
public state(): number {
if (!this.ws) {
return -1;
}
return this.ws.readyState;
}
// 手动关闭socket