2025-11-16 19:33:43 +08:00

118 lines
3.5 KiB
C#

using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NanoidDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using Dto.SignalRNet;
using MessagePack;
namespace XPrint.Production.Business.Net
{
public class XWebClient : IDisposable
{
public static readonly XWebClient Instance = new XWebClient();
//#if DEBUG
// public const string BASE_URL = "http://localhost:5020";
//#else
public const string BASE_URL = "https://tankapi.xy88.fun:8179";
//#endif
private HubConnection? hubConnection = null;
public event Action? ReconnectingEvent = null;
public event Action? ReconnectedEvent = null;
public event Action? ClosedEvent = null;
public event Action? LogindEvent = null;
public static readonly string uid = "931QzlBM2N9zyzKRgx9hZ";// Nanoid.Generate();
public static readonly string roomId = "room_boradcast";
private ConcurrentDictionary<string, Func<byte[]?, Task>> receiveEvents = new ConcurrentDictionary<string, Func<byte[]?, Task>>();
public async Task Init()
{
Dispose();
hubConnection = new HubConnectionBuilder()
.WithUrl($"{BASE_URL}/MsgHub")
.AddMessagePackProtocol()
.WithAutomaticReconnect(new SignalRRetryPolicy())
.ConfigureLogging((logging) =>
{
// 设置日志最低级别
logging.SetMinimumLevel(LogLevel.Error);
})
.Build();
receiveEvents.Clear();//清空所有事件
hubConnection.On(NetEventKeys.LOGIN_SUCCESS, () => {
LogindEvent?.Invoke();
});
hubConnection.On(NetEventKeys.RECEIVE_MSG, async (BaseMessage<byte[]> packet) =>
{
var msgType = packet.MsgType;
if (receiveEvents.TryGetValue(packet.MsgType, out var action))
{
await action?.Invoke(packet.Data)!;
}
});
hubConnection.Reconnecting += (state) =>
{
ReconnectingEvent?.Invoke();
return Task.CompletedTask;
};
hubConnection.Reconnected += async (state) =>
{
await Login(uid, roomId);
ReconnectedEvent?.Invoke();
};
hubConnection.Closed += async (state) =>
{
//Console.WriteLine($"连接状态变化:{hubConnection.State}");
ClosedEvent?.Invoke();
await Init();
};
await hubConnection.StartAsync();
await Login(uid, roomId);
}
public void BindEvent(string msgType, Func<byte[]?, Task> action)
{
receiveEvents[msgType] = action;
}
public void UnBindEvent(string msgType)
{
receiveEvents.TryRemove(msgType, out _);
}
public async Task Login(string userId, string roomId)
{
await hubConnection!.SendAsync("login", new
{
userId,
roomId
});
}
public async void Dispose()
{
if (hubConnection != null)
{
await hubConnection.DisposeAsync();
hubConnection = null;
}
}
}
}