2024-06-15 13:02:35 +08:00
|
|
|
|
import * as SignalR from '@microsoft/signalr';
|
|
|
|
|
|
import { ElNotification } from 'element-plus';
|
|
|
|
|
|
import { getToken } from '/@/utils/axios-utils';
|
|
|
|
|
|
|
|
|
|
|
|
// 初始化SignalR对象
|
|
|
|
|
|
const connection = new SignalR.HubConnectionBuilder()
|
|
|
|
|
|
.configureLogging(SignalR.LogLevel.Information)
|
2024-07-15 11:38:17 +08:00
|
|
|
|
.withUrl(`${window.__env__.VITE_API_URL}/hubs/onlineUser?token=${getToken()}`, { transport: SignalR.HttpTransportType.WebSockets, skipNegotiation: true })
|
2024-06-15 13:02:35 +08:00
|
|
|
|
.withAutomaticReconnect({
|
|
|
|
|
|
nextRetryDelayInMilliseconds: () => {
|
|
|
|
|
|
return 5000; // 每5秒重连一次
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
|
|
connection.keepAliveIntervalInMilliseconds = 15 * 1000; // 心跳检测15s
|
|
|
|
|
|
connection.serverTimeoutInMilliseconds = 30 * 60 * 1000; // 超时时间30m
|
2024-07-18 00:51:07 +08:00
|
|
|
|
// 若30s内没有收到服务器端发过来的信息,则认为服务器端异常
|
|
|
|
|
|
connection.serverTimeoutInMilliseconds = 30 * 1000;
|
|
|
|
|
|
// 若15s内没有向服务器发送任何消息,则ping一下服务器端
|
|
|
|
|
|
connection.keepAliveIntervalInMilliseconds = 15 * 1000;
|
2024-06-15 13:02:35 +08:00
|
|
|
|
|
|
|
|
|
|
// 启动连接
|
|
|
|
|
|
connection.start().then(() => {
|
|
|
|
|
|
console.log('启动连接');
|
|
|
|
|
|
});
|
|
|
|
|
|
// 断开连接
|
|
|
|
|
|
connection.onclose(async () => {
|
|
|
|
|
|
console.log('断开连接');
|
|
|
|
|
|
});
|
|
|
|
|
|
// 重连中
|
|
|
|
|
|
connection.onreconnecting(() => {
|
|
|
|
|
|
ElNotification({
|
|
|
|
|
|
title: '提示',
|
|
|
|
|
|
message: '服务器已断线...',
|
|
|
|
|
|
type: 'error',
|
|
|
|
|
|
position: 'bottom-right',
|
|
|
|
|
|
});
|
|
|
|
|
|
});
|
|
|
|
|
|
// 重连成功
|
|
|
|
|
|
connection.onreconnected(() => {
|
|
|
|
|
|
console.log('重连成功');
|
|
|
|
|
|
});
|
2025-05-15 00:25:13 +08:00
|
|
|
|
// 用户列表
|
2024-06-15 13:02:35 +08:00
|
|
|
|
connection.on('OnlineUserList', () => {});
|
2024-07-18 00:51:07 +08:00
|
|
|
|
// 接收消息
|
|
|
|
|
|
connection.on('ReceiveMessage', (message: any) => {
|
2024-07-25 16:55:56 +08:00
|
|
|
|
var tmpMsg = `<div style="white-space: pre-wrap;">${message.message}<div><br/>`;
|
2025-08-13 03:36:50 +08:00
|
|
|
|
tmpMsg += `<p style="color:#808080; font-size:10px;float:right"> ${message.sendUserName} ${message.sendTime}<p>`;
|
2024-07-18 00:51:07 +08:00
|
|
|
|
|
|
|
|
|
|
ElNotification({
|
2025-08-13 03:36:50 +08:00
|
|
|
|
title: `${message.title}`,
|
2024-07-18 00:51:07 +08:00
|
|
|
|
message: tmpMsg,
|
2025-08-13 03:36:50 +08:00
|
|
|
|
type: message.messageType.toString().toLowerCase(),
|
2024-07-18 00:51:07 +08:00
|
|
|
|
position: 'top-right',
|
|
|
|
|
|
dangerouslyUseHTMLString: true,
|
|
|
|
|
|
duration: 0,
|
|
|
|
|
|
});
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2024-06-15 13:02:35 +08:00
|
|
|
|
export { connection as signalR };
|