using Microsoft.AspNetCore.SignalR;
namespace OASystem.API.OAMethodLib.Hubs
{
///
/// 定义集线器
///
public class MyHub : Hub
{
///
/// 用户字典
///
private static Dictionary dictUsers = new Dictionary();
///
/// 建立连接回调
///
///
public override Task OnConnectedAsync()
{
Console.WriteLine($"ID:{Context.ConnectionId} 已连接");
return base.OnConnectedAsync();
}
///
/// 断开连接回调
///
///
///
public override Task OnDisconnectedAsync(Exception? exception)
{
Console.WriteLine($"ID:{Context.ConnectionId} 已断开");
return base.OnDisconnectedAsync(exception);
}
///
/// 登录功能,将用户ID和ConntectionId关联起来
///
///
public void Login(string userId)
{
if (!dictUsers.ContainsKey(userId))
{
dictUsers[userId] = Context.ConnectionId;
}
Console.WriteLine($"{userId}登录成功,ConnectionId={Context.ConnectionId}");
//向所有用户发送当前在线的用户列表
Clients.All.SendAsync("Users", dictUsers.Keys.ToList());
}
///
/// 退出功能,当客户端退出时调用
///
///
public void Logout(string userId)
{
if (dictUsers.ContainsKey(userId))
{
dictUsers.Remove(userId);
}
Console.WriteLine($"{userId}退出成功,ConnectionId={Context.ConnectionId}");
}
}
}