feat: ws工具新增连接状态函数
This commit is contained in:
@@ -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) {
|
if (!this.ws) {
|
||||||
console.warn('websocket unavailable');
|
console.warn('websocket unavailable');
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 非正常状态关闭
|
// 非正常状态关闭
|
||||||
@@ -173,7 +177,7 @@ export class WS {
|
|||||||
this.ws.readyState === WebSocket.CLOSING
|
this.ws.readyState === WebSocket.CLOSING
|
||||||
) {
|
) {
|
||||||
this.close();
|
this.close();
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
// 正在连接时
|
// 正在连接时
|
||||||
if (this.ws.readyState === WebSocket.CONNECTING) {
|
if (this.ws.readyState === WebSocket.CONNECTING) {
|
||||||
@@ -184,7 +188,21 @@ export class WS {
|
|||||||
// 在连接的
|
// 在连接的
|
||||||
if (this.ws.readyState === WebSocket.OPEN) {
|
if (this.ws.readyState === WebSocket.OPEN) {
|
||||||
this.ws.send(JSON.stringify(data));
|
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
|
// 手动关闭socket
|
||||||
|
|||||||
Reference in New Issue
Block a user