HJ_Server/src/setWsClient.ts
2023-12-13 20:51:17 +08:00

49 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { LogLevel, WsClient, WsClientStatus } from 'tsrpc';
import { serviceProto } from './cross/protocols/serviceProto';
import { ChatFun } from './public/chat';
/**创建跨服连接对象 */
export async function createWsClient() {
G.clientCross = new WsClient(serviceProto, {
server: G.config.corssWsUrl,
logLevel: G.argv.logModel as LogLevel,
json: true,
timeout:15000,
// 心跳检测防止长时间无交互tcp协议被挂起
heartbeat: {
// 两次心跳检测的间隔时间(毫秒)
interval: 8000,
// 发出心跳检测包后,多长时间未收到回复视为超时(毫秒),超时将使连接断开
timeout: 40000
}
});
let result = await G.clientCross.connect();
if (!result.isSucc) return console.log('connect cross server fail: ', result.errMsg);
else console.log(`connect cross server succ at ${G.config.corssWsUrl}`);
G.clientCross.listenMsg('msg_cross/CrossChat', sendData => {
//收到跨服推过来的“世界”聊天
ChatFun.newMsg(sendData);
});
}
let count = 0;
/**
* SchedulerManage.start里每1秒会在调用这个方法一次
*/
export function checkCrossWsIsDisconnect() {
count++;
if (count == 5) {
//每5s判断一次是否需要重连
if (G.config.corssWsUrl && G.clientCross?.status == WsClientStatus.Closed) {
try {
G.clientCross.connect();
} catch (error) {
}
}
count = 0;
}
}