關於SignalR的簡單實用 請參考 Asp.NET MVC 使用 SignalR 實現推送功能一(Hubs 在線聊天室)html
在上一篇中,咱們只是介紹了簡單的消息推送,今天咱們來修改一下,實現保存消息,歷史消息和用戶在線服務器
因爲,我這是在一個項目(【無私分享:從入門到精通ASP.NET MVC】從0開始,一塊兒搭框架、作項目 目錄索引)的基礎上作的,因此使用到的一些藉口和數據表,不詳細解析,只是介紹一下思路和實現方式,供你們參考app
當用戶登陸以後,咱們註冊一下用戶的信息,咱們在ChatHub中 新建一個方法 Register(用戶賬號,用戶密碼)框架
前臺js調用這個方法實現用戶註冊 ide
1 $.connection.hub.start().done(function () { 2 chat.server.register('用戶賬號', '用戶密碼'); 3 });
Register方法的實現:post
1 /// <summary> 2 /// 用戶登陸註冊信息 3 /// </summary> 4 /// <param name="id"></param> 5 public void Register(string account,string password) 6 { 7 try 8 { 9 //獲取用戶信息 10 var User = UserManage.Get(p => p.ACCOUNT == account); 11 if (User != null && User.PASSWORD == password) 12 { 13 //更新在線狀態 14 var UserOnline = UserOnlineManage.LoadListAll(p => p.FK_UserId == User.ID).FirstOrDefault(); 15 UserOnline.ConnectId = Context.ConnectionId; 16 UserOnline.OnlineDate = DateTime.Now; 17 UserOnline.IsOnline = true; 18 UserOnline.UserIP = Utils.GetIP(); 19 UserOnlineManage.Update(UserOnline); 20 21 22 //超級管理員 23 if (User.ID == ClsDic.DicRole["超級管理員"]) 24 { 25 //通知用戶上線 26 Clients.All.UserLoginNotice("超級管理員:" + User.NAME + " 上線了!"); 27 28 } 29 else 30 { 31 //獲取用戶一級部門信息 32 var Depart = GetUserDepart(User.DPTID); 33 if (Depart != null && !string.IsNullOrEmpty(Depart.ID)) 34 { 35 //添加用戶到部門羣組 Groups.Add(用戶鏈接ID,羣組) 36 Groups.Add(Context.ConnectionId, Depart.ID); 37 //通知用戶上線 38 Clients.All.UserLoginNotice(Depart.NAME + " - " + CodeManage.Get(m => m.CODEVALUE == User.LEVELS && m.CODETYPE == "ZW").NAMETEXT + ":" + User.NAME + " 上線了!"); 39 40 41 } 42 } 43 //刷新用戶通信錄 44 Clients.All.ContactsNotice(JsonConverter.Serialize(UserOnline)); 45 } 46 } 47 catch(Exception ex) 48 { 49 Clients.Client(Context.ConnectionId).UserLoginNotice("出錯了:" + ex.Message); 50 throw ex.InnerException; 51 } 52 53 }
用戶上線通知,你們能夠在對話框內已係統消息的方式提示,我這裏是一個toastr插件的提示this
1 //用戶上線通知 2 chat.client.UserLoginNotice = function (message) { 3 if ($("#LoginNotice").prop("checked")) { toasSuccess.message_t(message); } 4 };
這裏面有個判斷,若是用戶容許提醒,就提示,若是不容許,就不提示,就是個checkboxspa
當用戶登陸後,刷新其它用戶通信錄用戶的在線狀態,離線用戶排到底部,而且若是用戶離線,點擊用戶的時候,提示用戶離線發送郵件仍是離線消息插件
1 //通信錄用戶上下線 2 chat.client.ContactsNotice = function (message) { 3 var data = eval("(" + message + ")"); 4 if (!data.IsOnline) { 5 var current = $("#charUser-" + data.FK_UserId).addClass("offline"); 6 var parentId = current.parent().parent().prop("id"); 7 current.remove().appendTo($("#" + parentId + " .panel-body")); 8 }else 9 { 10 var current = $("#charUser-" + data.FK_UserId).removeClass("offline").attr("data-connectid", data.ConnectId); 11 var parentId = current.parent().parent().prop("id"); 12 current.insertBefore($("#" + parentId + " .panel-body .offline").eq(0)); 13 } 14 $(".panel-body .chat-user").click(function () { 15 if ($(this).hasClass("offline")) { 16 var MailId = $(this).attr("data-Email"); 17 var ConnectId = $(this).attr("data-connectid"); 18 var UserName = $(this).attr("data-username"); 19 swal({ title: "用戶離線", text: "當前用戶不在線,是否發送郵件?", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "發送郵件", cancelButtonText: "發送離線消息", closeOnConfirm: false, closeOnCancel: false }, function (isConfirm) { if (isConfirm) { sweetAlert.close(); document.getElementById(MailId).click(); } else { sweetAlert.close(); ChatPerson(ConnectId, UserName); } }); 20 } 21 else { 22 ChatPerson($(this).attr("data-connectid"), $(this).attr("data-username")); 23 } 24 }); 25 26 };
在線:3d
離線:
咱們重寫OnDisconnected方法,當用戶離線時,更新用戶狀態 同時刷新其它用戶通信錄用戶在線狀態
1 //使用者離線 2 public override Task OnDisconnected(bool stopCalled) 3 { 4 //更新在線狀態 5 var UserOnline = UserOnlineManage.LoadListAll(p => p.ConnectId == Context.ConnectionId).FirstOrDefault(); 6 UserOnline.ConnectId = Context.ConnectionId; 7 UserOnline.OfflineDate = DateTime.Now; 8 UserOnline.IsOnline = false; 9 UserOnlineManage.Update(UserOnline); 10 11 //獲取用戶信息 12 var User = UserManage.Get(p => p.ID == UserOnline.FK_UserId); 13 14 Clients.All.UserLogOutNotice(User.NAME + ":離線了!"); 15 //刷新用戶通信錄 16 Clients.All.ContactsNotice(JsonConverter.Serialize(UserOnline)); 17 18 return base.OnDisconnected(true); 19 }
前臺離線通知
1 //用戶離線通知 2 chat.client.UserLogOutNotice = function (message) { 3 if ($("#LogOutNotice").prop("checked")) { toasInfo.message_t(message); } 4 };
我是在用戶登陸的時候獲取用戶消息的,你們能夠放到其它邏輯中
Register方法添加用戶歷史消息
1 /// <summary> 2 /// 用戶登陸註冊信息 3 /// </summary> 4 /// <param name="id"></param> 5 public void Register(string account,string password) 6 { 7 try 8 { 9 //獲取用戶信息 10 var User = UserManage.Get(p => p.ACCOUNT == account); 11 if (User != null && User.PASSWORD == password) 12 { 13 //更新在線狀態 14 var UserOnline = UserOnlineManage.LoadListAll(p => p.FK_UserId == User.ID).FirstOrDefault(); 15 UserOnline.ConnectId = Context.ConnectionId; 16 UserOnline.OnlineDate = DateTime.Now; 17 UserOnline.IsOnline = true; 18 UserOnline.UserIP = Utils.GetIP(); 19 UserOnlineManage.Update(UserOnline); 20 21 //獲取歷史消息 22 int days = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["HistoryDays"]); 23 DateTime dtHistory = DateTime.Now.AddDays(-days); 24 var ChatMessageList = ChatMessageManage.LoadAll(p => p.MessageDate > dtHistory); 25 26 //超級管理員 27 if (User.ID == ClsDic.DicRole["超級管理員"]) 28 { 29 //通知用戶上線 30 Clients.All.UserLoginNotice("超級管理員:" + User.NAME + " 上線了!"); 31 32 var HistoryMessage = ChatMessageList.OrderBy(p=>p.MessageDate).ToList().Select(p => new 33 { 34 UserName = UserManage.Get(m => m.ID == p.FromUser).NAME, 35 UserFace = string.IsNullOrEmpty(UserManage.Get(m => m.ID == p.FromUser).FACE_IMG) ? "/Pro/Project/User_Default_Avatat?name=" + UserManage.Get(m => m.ID == p.FromUser).NAME.Substring(0, 1) : UserManage.Get(m => m.ID == p.FromUser).FACE_IMG, 36 MessageType=GetMessageType(p.MessageType), 37 p.FromUser, 38 p.MessageContent, 39 MessageDate = p.MessageDate.GetDateTimeFormats('D')[1].ToString() + " - " + p.MessageDate.ToString("HH:mm:ss"), 40 ConnectId = UserOnlineManage.LoadListAll(m => m.SYS_USER.ID == p.FromUser).FirstOrDefault().ConnectId 41 }).ToList(); 42 43 //推送歷史消息 44 Clients.Client(Context.ConnectionId).addHistoryMessageToPage(JsonConverter.Serialize(HistoryMessage)); 45 } 46 else 47 { 48 //獲取用戶一級部門信息 49 var Depart = GetUserDepart(User.DPTID); 50 if (Depart != null && !string.IsNullOrEmpty(Depart.ID)) 51 { 52 //添加用戶到部門羣組 Groups.Add(用戶鏈接ID,羣組) 53 Groups.Add(Context.ConnectionId, Depart.ID); 54 //通知用戶上線 55 Clients.All.UserLoginNotice(Depart.NAME + " - " + CodeManage.Get(m => m.CODEVALUE == User.LEVELS && m.CODETYPE == "ZW").NAMETEXT + ":" + User.NAME + " 上線了!"); 56 //用戶歷史消息 57 int typeOfpublic = Common.Enums.ClsDic.DicMessageType["廣播"]; 58 int typeOfgroup = Common.Enums.ClsDic.DicMessageType["羣組"]; 59 int typeOfprivate = Common.Enums.ClsDic.DicMessageType["私聊"]; 60 var HistoryMessage = ChatMessageList.Where(p => p.MessageType == typeOfpublic || (p.MessageType == typeOfgroup && p.ToGroup == Depart.ID) || (p.MessageType == typeOfprivate && p.ToGroup == User.ID.ToString())).OrderBy(p => p.MessageDate).ToList().Select(p => new 61 { 62 UserName = UserManage.Get(m => m.ID == p.FromUser).NAME, 63 UserFace = string.IsNullOrEmpty(UserManage.Get(m => m.ID == p.FromUser).FACE_IMG) ? "/Pro/Project/User_Default_Avatat?name=" + UserManage.Get(m => m.ID == p.FromUser).NAME.Substring(0, 1) : UserManage.Get(m => m.ID == p.FromUser).FACE_IMG, 64 MessageType = GetMessageType(p.MessageType), 65 p.FromUser, 66 p.MessageContent, 67 MessageDate = p.MessageDate.GetDateTimeFormats('D')[1].ToString() + " - " + p.MessageDate.ToString("HH:mm:ss"), 68 ConnectId = UserOnlineManage.LoadListAll(m => m.SYS_USER.ID == p.FromUser).FirstOrDefault().ConnectId 69 }).ToList(); 70 71 //推送歷史消息 72 Clients.Client(Context.ConnectionId).addHistoryMessageToPage(JsonConverter.Serialize(HistoryMessage)); 73 74 } 75 } 76 //刷新用戶通信錄 77 Clients.All.ContactsNotice(JsonConverter.Serialize(UserOnline)); 78 } 79 } 80 catch(Exception ex) 81 { 82 Clients.Client(Context.ConnectionId).UserLoginNotice("出錯了:" + ex.Message); 83 throw ex.InnerException; 84 } 85 86 }
前臺:
1 //接收歷史信息 2 chat.client.addHistoryMessageToPage = function (message) { 3 var data = eval("(" + message + ")"); 4 var html = ''; 5 for(var i=0;i<data.length;i++) 6 { 7 //處理消息 8 } 9 $(html).appendTo(".chat-discussion"); 10 $('<div class=" col-xs-12 m-t-sm m-b-sm text-center sysmessage"> — 以上是歷史消息 — </div>').appendTo(".chat-discussion"); 11 };
1 /// <summary> 2 /// 發送消息(廣播、組播) 3 /// </summary> 4 /// <param name="message">發送的消息</param> 5 /// <param name="message">發送的羣組</param> 6 public void Send(string message,string groupId) 7 { 8 try 9 { 10 //消息用戶主體 11 var UserOnline = UserOnlineManage.LoadListAll(p => p.ConnectId == Context.ConnectionId).FirstOrDefault(); 12 13 //廣播 14 if(string.IsNullOrEmpty(groupId)) 15 { 16 //保存消息 17 ChatMessageManage.Save(new Domain.SYS_CHATMESSAGE() { FromUser = UserOnline.FK_UserId, MessageType = Common.Enums.ClsDic.DicMessageType["廣播"], MessageContent = message, MessageDate = DateTime.Now, MessageIP = Utils.GetIP() }); 18 //返回消息實體 19 var Message = new Message() { ConnectId = UserOnline.ConnectId, UserName = UserOnline.SYS_USER.NAME, UserFace = string.IsNullOrEmpty(UserOnline.SYS_USER.FACE_IMG) ? "/Pro/Project/User_Default_Avatat?name=" + UserOnline.SYS_USER.NAME.Substring(0, 1) : UserOnline.SYS_USER.FACE_IMG, MessageDate = DateTime.Now.GetDateTimeFormats('D')[1].ToString() + " - " + DateTime.Now.ToString("HH:mm:ss"), MessageContent = message, MessageType = "public", UserId = UserOnline.SYS_USER.ID }; 20 21 //推送消息 22 Clients.All.addNewMessageToPage(JsonConverter.Serialize(Message)); 23 } 24 //組播 25 else 26 { 27 //保存消息 28 ChatMessageManage.Save(new Domain.SYS_CHATMESSAGE() { FromUser = UserOnline.FK_UserId, MessageType = Common.Enums.ClsDic.DicMessageType["羣組"], MessageContent = message, MessageDate = DateTime.Now, MessageIP = Utils.GetIP(), ToGroup = groupId }); 29 //返回消息實體 30 var Message = new Message() { ConnectId = UserOnline.ConnectId, UserName = UserOnline.SYS_USER.NAME, UserFace = string.IsNullOrEmpty(UserOnline.SYS_USER.FACE_IMG) ? "/Pro/Project/User_Default_Avatat?name=" + UserOnline.SYS_USER.NAME.Substring(0, 1) : UserOnline.SYS_USER.FACE_IMG, MessageDate = DateTime.Now.GetDateTimeFormats('D')[1].ToString() + " - " + DateTime.Now.ToString("HH:mm:ss"), MessageContent = message, MessageType = "group", UserId = UserOnline.SYS_USER.ID }; 31 32 //推送消息 33 Clients.Group(groupId).addNewMessageToPage(JsonConverter.Serialize(Message)); 34 //若是用戶不在羣組中則單獨推送消息給用戶 35 var Depart = GetUserDepart(UserOnline.SYS_USER.DPTID); 36 if(Depart==null) 37 { 38 //推送給用戶 39 Clients.Client(Context.ConnectionId).addNewMessageToPage(JsonConverter.Serialize(Message)); 40 } 41 else if(Depart.ID!=groupId) 42 { 43 //推送給用戶 44 Clients.Client(Context.ConnectionId).addNewMessageToPage(JsonConverter.Serialize(Message)); 45 } 46 } 47 } 48 catch(Exception ex) 49 { 50 //推送系統消息 51 Clients.Client(Context.ConnectionId).addSysMessageToPage("系統消息:消息發送失敗,請稍後再試!"); 52 throw ex.InnerException; 53 } 54 }
1 /// <summary> 2 /// 發送給指定用戶(單播) 3 /// </summary> 4 /// <param name="clientId">接收用戶的鏈接ID</param> 5 /// <param name="message">發送的消息</param> 6 public void SendSingle(string clientId, string message) 7 { 8 try 9 { 10 //接收用戶鏈接爲空 11 if (string.IsNullOrEmpty(clientId)) 12 { 13 //推送系統消息 14 Clients.Client(Context.ConnectionId).addSysMessageToPage("系統消息:用戶不存在!"); 15 } 16 else 17 { 18 //消息用戶主體 19 var UserOnline = UserOnlineManage.LoadListAll(p => p.ConnectId == Context.ConnectionId).FirstOrDefault(); 20 //接收消息用戶主體 21 var ReceiveUser = UserOnlineManage.LoadListAll(p => p.ConnectId == clientId).FirstOrDefault(); 22 if (ReceiveUser == null) 23 { 24 //推送系統消息 25 Clients.Client(Context.ConnectionId).addSysMessageToPage("系統消息:用戶不存在!"); 26 } 27 else 28 { 29 //保存消息 30 ChatMessageManage.Save(new Domain.SYS_CHATMESSAGE() { FromUser = UserOnline.FK_UserId, MessageType = Common.Enums.ClsDic.DicMessageType["私聊"], MessageContent = message, MessageDate = DateTime.Now, MessageIP = Utils.GetIP(), ToGroup = UserOnline.SYS_USER.ID.ToString() }); 31 //返回消息實體 32 var Message = new Message() { ConnectId = UserOnline.ConnectId, UserName = UserOnline.SYS_USER.NAME, UserFace = string.IsNullOrEmpty(UserOnline.SYS_USER.FACE_IMG) ? "/Pro/Project/User_Default_Avatat?name=" + UserOnline.SYS_USER.NAME.Substring(0, 1) : UserOnline.SYS_USER.FACE_IMG, MessageDate = DateTime.Now.GetDateTimeFormats('D')[1].ToString() + " - " + DateTime.Now.ToString("HH:mm:ss"), MessageContent = message, MessageType = "private", UserId = UserOnline.SYS_USER.ID }; 33 if (ReceiveUser.IsOnline) 34 { 35 //推送給指定用戶 36 Clients.Client(clientId).addNewMessageToPage(JsonConverter.Serialize(Message)); 37 } 38 //推送給用戶 39 Clients.Client(Context.ConnectionId).addNewMessageToPage(JsonConverter.Serialize(Message)); 40 41 } 42 } 43 } 44 catch (Exception ex) 45 { 46 //推送系統消息 47 Clients.Client(Context.ConnectionId).addSysMessageToPage("系統消息:消息發送失敗,請稍後再試!"); 48 throw ex.InnerException; 49 } 50 }
前臺發送消息:
1 $.connection.hub.start().done(function () { 2 chat.server.register('用戶賬號', '用戶密碼'); 3 //文本框回車推送 4 $("#sendMessage").keyup(function (event) { 5 if (event.keyCode == 13 || event.which == 13) 6 { 7 if ($.trim($(this).val()) == '' || $.trim($(this).val()).length < 1) { 8 $(this).val($.trim($(this).val())); 9 $(this).focus(); 10 return false; 11 } 12 else { 13 //私聊 14 if ($.trim($("#person").val()) != '' && $.trim($("#person").val()).length > 1) { 15 chat.server.sendSingle($("#person").val(), $(this).val()); 16 } 17 else { 18 chat.server.send($(this).val(), $("#group").val()); 19 } 20 $(this).val("").focus(); 21 } 22 23 } 24 }); 25 26 });
前臺接收消息:
1 //接收服務器信息 2 chat.client.addNewMessageToPage = function (message) { 3 var data = eval("(" + message + ")"); 4 var html = '';
5 //處理消息
19 $(html).appendTo(".chat-discussion"); 20 $('.chat-discussion').scrollTop($('.chat-discussion')[0].scrollHeight); 21 if(!$("#small-chat-box").hasClass("active")) 22 { 23 messagecount = messagecount + 1; 24 } 25 if (messagecount > 0) 26 { 27 $("#small-chat .badge").html(messagecount); 28 } 29 }; 30 //接收系統消息 31 chat.client.addSysMessageToPage = function (message) { 32 $('<div class=" col-xs-12 m-t-sm m-b-sm text-center sysmessage">' + message + '</div>').appendTo(".chat-discussion"); 33 $('.chat-discussion').scrollTop($('.chat-discussion')[0].scrollHeight); 34 };
離線:
上線:
私聊:
組聊:
原創文章 轉載請尊重勞動成果 http://yuangang.cnblogs.com