leiy 1 year ago
parent
commit
af7b83a2dd

+ 9 - 43
OASystem/OASystem.Api/Controllers/AuthController.cs

@@ -17,6 +17,7 @@ using System.Globalization;
 using Microsoft.AspNetCore.SignalR;
 using Microsoft.AspNetCore.SignalR;
 using OASystem.API.OAMethodLib.Hub.Hubs;
 using OASystem.API.OAMethodLib.Hub.Hubs;
 using OASystem.API.OAMethodLib.Hub.HubClients;
 using OASystem.API.OAMethodLib.Hub.HubClients;
+using static OASystem.API.OAMethodLib.Hub.Hubs.ChatHub;
 
 
 namespace OASystem.API.Controllers
 namespace OASystem.API.Controllers
 {
 {
@@ -32,12 +33,13 @@ namespace OASystem.API.Controllers
         private readonly MessageRepository _message;
         private readonly MessageRepository _message;
         private readonly SystemMenuPermissionRepository _SystemMenuPermissionRepository;
         private readonly SystemMenuPermissionRepository _SystemMenuPermissionRepository;
         private readonly MessageRepository _messageRep;
         private readonly MessageRepository _messageRep;
-        
         private readonly IQiYeWeChatApiService _qiYeWeChatApiServic;
         private readonly IQiYeWeChatApiService _qiYeWeChatApiServic;
-      
+        private readonly IHubContext<ChatHub, IChatClient> _hubContext;
+
 
 
         public AuthController(IConfiguration config, LoginRepository loginRep, IMapper mapper,MessageRepository message,
         public AuthController(IConfiguration config, LoginRepository loginRep, IMapper mapper,MessageRepository message,
-            SystemMenuPermissionRepository systemMenuPermissionRepository, IQiYeWeChatApiService qiYeWeChatApiService, MessageRepository messageRep)
+            SystemMenuPermissionRepository systemMenuPermissionRepository, IQiYeWeChatApiService qiYeWeChatApiService, MessageRepository messageRep,
+            IHubContext<ChatHub, IChatClient> hubContext)
         {
         {
             _config = config;
             _config = config;
             _loginRep = loginRep;
             _loginRep = loginRep;
@@ -46,7 +48,7 @@ namespace OASystem.API.Controllers
             _SystemMenuPermissionRepository = systemMenuPermissionRepository;
             _SystemMenuPermissionRepository = systemMenuPermissionRepository;
             _qiYeWeChatApiServic = qiYeWeChatApiService;
             _qiYeWeChatApiServic = qiYeWeChatApiService;
             _messageRep = messageRep;
             _messageRep = messageRep;
-            
+            _hubContext = hubContext;
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -118,11 +120,9 @@ namespace OASystem.API.Controllers
             }
             }
 
 
 
 
-            #region 添加登录用户上线信息
-
-
-
-            #endregion
+            //#region 添加登录用户上线信息
+            //_hubContext.SignalRLogin(uId);
+            //#endregion
 
 
             #region 测试添加系统消息
             #region 测试添加系统消息
 
 
@@ -206,9 +206,6 @@ namespace OASystem.API.Controllers
 
 
             }
             }
 
 
-
-
-
             return Ok(new { Code = 200, Msg = "查询成功!", Data = detailsView1 });
             return Ok(new { Code = 200, Msg = "查询成功!", Data = detailsView1 });
         }
         }
 
 
@@ -735,36 +732,5 @@ namespace OASystem.API.Controllers
             
             
         }
         }
 
 
-
-        /// <summary>
-        /// 测试 
-        /// 发送消息
-        /// </summary>
-        /// <param name="date"></param>
-        /// <param name="hubContext"></param>
-        /// <returns></returns>
-        [HttpPost("SendMessage")]
-        public async Task SendMessage(string date, [FromServices] IHubContext<ChatHub, IChatClient> hubContext)
-        {
-
-            await hubContext.Clients.All.SendAll(date);
-
-        }
-
-
-        /// <summary>
-        /// 测试 
-        /// 发送指定消息给指定的用户
-        /// </summary>
-        /// <param name="date"></param>
-        /// <param name="hubContext"></param>
-        /// <returns></returns>
-        [HttpPost("SendMessageByUser")]
-        public async Task<IActionResult> SendMessageByUser(string username,string date, [FromServices] IHubContext<ChatHub, IChatClient> hubContext)
-        {
-            await hubContext.Clients.User(username).SendMessageByUser(date);
-
-            return Ok("Send Successful!");
-        }
     }
     }
 }
 }

+ 72 - 0
OASystem/OASystem.Api/Controllers/ClientHubController.cs

@@ -0,0 +1,72 @@
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.SignalR;
+using OASystem.API.OAMethodLib.Hub.HubClients;
+using OASystem.API.OAMethodLib.Hub.Hubs;
+using OASystem.API.OAMethodLib.SignalR.Hubs;
+
+namespace OASystem.API.Controllers
+{
+    /// <summary>
+    /// 消息客户端
+    /// </summary>
+    [Route("api/[controller]/[action]")]
+    public class ClientHubController : ControllerBase
+    {
+        private readonly ILogger<ClientHubController> _logger;
+        private readonly IHubContext<ChatHub, IChatClient> _hubContext;
+
+        public ClientHubController(ILogger<ClientHubController> logger, IHubContext<ChatHub, IChatClient> hubContext )
+        {
+            _logger = logger;
+            _hubContext = hubContext;
+        }
+
+        /// <summary>
+        /// 获取所有的用户
+        /// </summary>
+        /// <returns></returns>
+        [HttpGet("GetAllUserIds", Name = "GetAllUserIds")]
+        public List<UserModel> GetAllUserIds()
+        {
+            return UserStore.OnlineUser;
+        }
+
+
+        /// <summary>
+        /// 发送消息给客户端
+        /// </summary>
+        /// <param name="userid"></param>
+        /// <param name="date"></param>
+        /// <param name="hubContext"></param>
+        /// <returns></returns>
+        [HttpPost("SendAllUserMessage", Name = "SendAllUserMessage")]
+        public async Task<IActionResult> SendAllUserMessage( string msg)
+        {
+            await _hubContext.Clients.All.SendAll(msg);
+            return Ok("Send Successful!");
+        }
+
+        /// <summary>
+        /// 发送指定的消息给指定的客户端
+        /// </summary>
+        /// <param name="userid"></param>
+        /// <param name="date"></param>
+        /// <param name="hubContext"></param>
+        /// <returns></returns>
+        [HttpPost("SendCustomUserMessage", Name = "SendCustomUserMessage")]
+        public async Task<IActionResult> SendCustomUserMessage(int userid,string date )
+        {
+            string connId = string.Empty;
+
+            UserModel user = UserStore.OnlineUser.Where(it => it.UserId == userid).FirstOrDefault();
+            if (user != null)
+            {
+                connId = user.ConnectionId;
+            }
+
+            await _hubContext.Clients.Client(connId).SendCustomUserMessage(date);
+            return Ok("Send Successful!");
+        }
+    }
+}

+ 6 - 0
OASystem/OASystem.Api/OAMethodLib/SignalR/HubClients/IChatClient.cs

@@ -2,8 +2,14 @@
 {
 {
     public interface IChatClient
     public interface IChatClient
     {
     {
+        Task SignalRLogin(int userId);
+
+        Task SendAsync(string method, object message);
+
         Task SendAll(object message);
         Task SendAll(object message);
 
 
         Task SendMessageByUser(object message);
         Task SendMessageByUser(object message);
+
+        Task SendCustomUserMessage(object message);
     }
     }
 }
 }

+ 4 - 0
OASystem/OASystem.Api/OAMethodLib/SignalR/HubService/CommonService.cs

@@ -2,6 +2,8 @@
 {
 {
     public class CommonService
     public class CommonService
     {
     {
+        internal object SendCaller(string data) => "Send Successful!";
+
         internal object SendAll(string data)
         internal object SendAll(string data)
         {
         {
             return $"Hello {new Random().Next(0, 100)} {data} ";
             return $"Hello {new Random().Next(0, 100)} {data} ";
@@ -11,5 +13,7 @@
         {
         {
             return $"Hello {new Random().Next(0, 100)} {data} ";
             return $"Hello {new Random().Next(0, 100)} {data} ";
         }
         }
+
+
     }
     }
 }
 }

+ 32 - 33
OASystem/OASystem.Api/OAMethodLib/SignalR/Hubs/ChatHub.cs

@@ -1,4 +1,5 @@
 using Microsoft.AspNetCore.SignalR;
 using Microsoft.AspNetCore.SignalR;
+using OASystem.API.OAMethodLib.Hub;
 using OASystem.API.OAMethodLib.Hub.HubClients;
 using OASystem.API.OAMethodLib.Hub.HubClients;
 using OASystem.API.OAMethodLib.SignalR.Hubs;
 using OASystem.API.OAMethodLib.SignalR.Hubs;
 using OASystem.API.OAMethodLib.SignalR.HubService;
 using OASystem.API.OAMethodLib.SignalR.HubService;
@@ -12,19 +13,17 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
     public class ChatHub : Hub<IChatClient>
     public class ChatHub : Hub<IChatClient>
     {
     {
         private readonly ILogger<ChatHub> _logger;
         private readonly ILogger<ChatHub> _logger;
-        private readonly IHttpContextAccessor _accessor;
         private readonly CommonService _common;
         private readonly CommonService _common;
+        
+        /// <summary>
+        /// 已登录的用户信息
+        /// </summary>
+        //public static List<UserModel> OnlineUser { get; set; } = new List<UserModel>();
 
 
-            /// <summary>
-           /// 已登录的用户信息
-           /// </summary>
-           public static List<UserModel> OnlineUser { get; set; } = new List<UserModel>();
-
-        public ChatHub(ILogger<ChatHub> logger, CommonService common, IHttpContextAccessor accessor)
+        public ChatHub(ILogger<ChatHub> logger, CommonService common)
         {
         {
             _logger = logger;
             _logger = logger;
             _common = common;
             _common = common;
-            _accessor = accessor;
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -33,15 +32,18 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
         public async Task SignalRLogin(int userId)
         public async Task SignalRLogin(int userId)
         {
         {
             string connid = Context.ConnectionId;
             string connid = Context.ConnectionId;
-            bool status = false;
-            if (!OnlineUser.Exists(u => u.ConnectionId == connid))
+            string result = $"[{connid}]";
+            if (!UserStore.OnlineUser.Exists(u => u.ConnectionId == connid))
             {
             {
-                status = true;
-                OnlineUser.Add( new UserModel() { UserId = userId,ConnectionId = connid,GroupName = "FMGJ-OASystem" });
-
+                result += "上线成功!" ;
+                UserStore.OnlineUser.Add( new UserModel() { UserId = userId,ConnectionId = connid,GroupName = "FMGJ-OASystem" });
+            }
+            else
+            {
+                result += "已上线!";
             }
             }
             //给当前连接返回消息
             //给当前连接返回消息
-            //await Clients.Client(connid).SendAsync("SignalRLoginResponse", status);
+            await Clients.Client(connid).SendAsync("SignalRLoginResponse", result);
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -50,14 +52,9 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
         /// <returns></returns>
         /// <returns></returns>
         public override Task OnConnectedAsync()
         public override Task OnConnectedAsync()
         {
         {
-            var id = Context.ConnectionId;
-            _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Connection Server!");
-
-            //验证Token
-            //var token = _accessor.HttpContext.Request.Query["access_token"];
-            //var user = JwtHelper.SerializeJwt(token);
-
-
+            var connid = Context.ConnectionId;
+            _logger.LogInformation($"Client ConnectionId=> [[{connid}]] Already Connection Server!");
+            
             return base.OnConnectedAsync();
             return base.OnConnectedAsync();
         }
         }
 
 
@@ -68,13 +65,21 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
         /// <returns></returns>
         /// <returns></returns>
         public override Task OnDisconnectedAsync(Exception exception)
         public override Task OnDisconnectedAsync(Exception exception)
         {
         {
-            var id = Context.ConnectionId;
-            _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Close Connection Server!");
+            var connid = Context.ConnectionId;
+            _logger.LogInformation($"Client ConnectionId=> [[{connid}]] Already Close Connection Server!");
+            var model = UserStore.OnlineUser.Find(u => u.ConnectionId == connid);
+            int count = UserStore.OnlineUser.RemoveAll(u => u.ConnectionId == connid);
+            if (model != null)
+            {
+
+                var onlineUser = UserStore.OnlineUser.FindAll(u => u.GroupName == model.GroupName);
+
+                Clients.Group(model.GroupName).SendAsync("GetUsersResponse", onlineUser);
+            }
             return base.OnDisconnectedAsync(exception);
             return base.OnDisconnectedAsync(exception);
         }
         }
 
 
        
        
-
         /**
         /**
          * 测试 
          * 测试 
          * */
          * */
@@ -86,16 +91,10 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
         {
         {
             Console.WriteLine("Have one Data!");
             Console.WriteLine("Have one Data!");
             await Clients.All.SendAll(_common.SendAll(data));
             await Clients.All.SendAll(_common.SendAll(data));
+            await Clients.Caller.SendAll(_common.SendCaller(data));
         }
         }
 
 
 
 
-        public class UserModel
-        {
-            public int UserId { get; set; }
-
-            public string ConnectionId { get; set; }
-
-            public string GroupName { get; set; }
-        }
+        
     }
     }
 }
 }

+ 0 - 58
OASystem/OASystem.Api/OAMethodLib/SignalR/Hubs/GroupStore.cs

@@ -1,58 +0,0 @@
-namespace OASystem.API.OAMethodLib.SignalR.Hubs
-{
-    /// <summary>
-    /// 分组
-    /// </summary>
-    public static class GroupStore
-    {
-        public static Dictionary<string, List<string>> Groups = new Dictionary<string, List<string>>();
-        public static void Add(string groupname, string Id)
-        {
-            if (Groups.ContainsKey(groupname))
-            {
-                if (Groups.TryGetValue(groupname, out var values))
-                {
-                    if (values.Contains(Id))
-                        return;
-                    values.Add(Id);
-                }
-                else
-                {
-                    throw new Exception("Add group Error");
-                }
-            }
-            else
-            {
-                var newvalues = new List<string>() { Id };
-                Groups.Add(groupname, newvalues);
-            }
-        }
-        public static void Remove(string groupname, string Id)
-        {
-            if (Groups.ContainsKey(groupname))
-            {
-                if (Groups.TryGetValue(groupname, out var values))
-                {
-                    if (!values.Contains(Id))
-                        return;
-                    values.Remove(Id);
-                    if (!(values.Count > 0))
-                        Groups.Remove(groupname);
-                }
-                else
-                {
-                    throw new Exception("Remove group Error");
-                }
-            }
-        }
-        /// <summary>
-        /// 连接断开时删除
-        /// </summary>
-        /// <param name="Id"></param>
-        public static void UnConnection(string Id)
-        {
-            Groups.Where(x => x.Value.Contains(Id)).AsParallel().ForAll(x => x.Value.Remove(Id));
-        }
-
-    }
-}

+ 20 - 0
OASystem/OASystem.Api/OAMethodLib/SignalR/Hubs/UserStore.cs

@@ -0,0 +1,20 @@
+namespace OASystem.API.OAMethodLib.SignalR.Hubs
+{
+    public class UserStore
+    {
+        public static List<UserModel> OnlineUser { get; set; } = new List<UserModel>();
+
+    }
+
+
+    public class UserModel
+    {
+        public int UserId { get; set; }
+
+        public string ConnectionId { get; set; }
+
+        public string GroupName { get; set; }
+
+        public DateTime OnlineTime { get; set; } = DateTime.Now;
+    }
+}

+ 0 - 4
OASystem/OASystem.Api/OASystem.API.csproj

@@ -55,10 +55,6 @@
     </Reference>
     </Reference>
   </ItemGroup>
   </ItemGroup>
 
 
-  <ItemGroup>
-    <Folder Include="OAMethodLib\新文件夹\" />
-  </ItemGroup>
-
   <ProjectExtensions><VisualStudio><UserProperties properties_4launchsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
   <ProjectExtensions><VisualStudio><UserProperties properties_4launchsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
 
 
 </Project>
 </Project>

+ 2 - 0
OASystem/OASystem.Api/Program.cs

@@ -24,6 +24,7 @@ using OASystem.API.OAMethodLib.Hub.Hubs;
 using Microsoft.Extensions.DependencyInjection.Extensions;
 using Microsoft.Extensions.DependencyInjection.Extensions;
 using OASystem.API.OAMethodLib.SignalR.HubService;
 using OASystem.API.OAMethodLib.SignalR.HubService;
 using OASystem.API.OAMethodLib.Auth;
 using OASystem.API.OAMethodLib.Auth;
+using OASystem.API.OAMethodLib.Hub.HubClients;
 
 
 var builder = WebApplication.CreateBuilder(args);
 var builder = WebApplication.CreateBuilder(args);
 var basePath = AppContext.BaseDirectory;
 var basePath = AppContext.BaseDirectory;
@@ -296,6 +297,7 @@ builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
 #endregion
 #endregion
 
 
 
 
+
 #region SignalR
 #region SignalR
 builder.Services.AddSignalR()
 builder.Services.AddSignalR()
                 .AddJsonProtocol(options =>
                 .AddJsonProtocol(options =>