fix: ws函数发送消息判断是否连接正常

This commit is contained in:
TsMask
2024-02-26 12:09:49 +08:00
parent dd6c38c57e
commit d55a4e3da7

View File

@@ -11,7 +11,7 @@ export type OptionsType = {
/**地址栏参数 */ /**地址栏参数 */
params?: Record<string, string | number | boolean | undefined>; params?: Record<string, string | number | boolean | undefined>;
/**onopen事件的回调函数 */ /**onopen事件的回调函数 */
onopen?: () => void; onopen?: Function;
/**message事件的回调函数 */ /**message事件的回调函数 */
onmessage: (data: Record<string, any>) => void; onmessage: (data: Record<string, any>) => void;
/**error事件的回调函数 */ /**error事件的回调函数 */
@@ -114,7 +114,7 @@ export class WS {
this.heartCheck(options.heartTimer); this.heartCheck(options.heartTimer);
} }
if (typeof options.onopen === 'function') { if (typeof options.onopen === 'function') {
options.onopen(); options.onopen(ev);
} }
}; };
// 用于指定当从服务器接受到信息时的回调函数。 // 用于指定当从服务器接受到信息时的回调函数。
@@ -166,7 +166,7 @@ export class WS {
console.warn('websocket unavailable'); console.warn('websocket unavailable');
return; return;
} }
// 非正常状态关闭 // 非正常状态关闭
if ( if (
this.ws.readyState === WebSocket.CLOSED || this.ws.readyState === WebSocket.CLOSED ||
@@ -175,8 +175,16 @@ export class WS {
this.close(); this.close();
return; return;
} }
// 正在连接时
this.ws.send(JSON.stringify(data)); if (this.ws.readyState === WebSocket.CONNECTING) {
setTimeout(() => {
this.ws && this.ws.send(JSON.stringify(data));
}, 1000);
}
// 在连接的
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
} }
// 手动关闭socket // 手动关闭socket