Asp.net使用SignalR實(shí)現(xiàn)酷炫端對(duì)端聊天功能

字號(hào):


    這篇文章主要為大家詳細(xì)介紹了Asp.net使用SignalR實(shí)現(xiàn)酷炫端對(duì)端聊天功能,感興趣的小伙伴們可以參考一下
    一、引言
    在前一篇文章已經(jīng)詳細(xì)介紹了SignalR了,并且簡(jiǎn)單介紹它在Asp.net MVC 和WPF中的應(yīng)用。在上篇博文介紹的都是群發(fā)消息的實(shí)現(xiàn),然而,對(duì)于SignalR是為了實(shí)時(shí)聊天而生的,自然少了不像QQ一樣的端對(duì)端的聊天了。本篇博文將介紹如何使用SignalR來(lái)實(shí)現(xiàn)類(lèi)似QQ聊天的功能。
    二、使用SignalR實(shí)現(xiàn)端對(duì)端聊天的思路
    在介紹具體實(shí)現(xiàn)之前,我先來(lái)介紹了使用SignalR實(shí)現(xiàn)端對(duì)端聊天的思路。相信大家在前篇文章已經(jīng)看到過(guò)Clients.All.sendMessage(name, message);這樣的代碼,其表示調(diào)用所有客戶(hù)端的SendMessage。SignalR的集線器使得客戶(hù)端和服務(wù)端可以進(jìn)行實(shí)時(shí)通信。那要實(shí)現(xiàn)端對(duì)端的聊天,自然就不能像所有客戶(hù)端發(fā)送消息了,而只能向特定的客戶(hù)端發(fā)送消息才可以,不然不就亂套了,沒(méi)有任何隱私權(quán)了。那怎樣才可以向特定的客戶(hù)端發(fā)送消息呢?這個(gè)問(wèn)題也就是我們實(shí)現(xiàn)端對(duì)端聊天功能的關(guān)鍵。
    我們發(fā)送Clients對(duì)象除了All屬性外,還具有其他屬性,你可以在VS中按F12來(lái)查看Clients對(duì)象的所有屬性或方法,具體的定義如下:
    public interface IHubConnectionContext<T>
    {
     T All { get; } // 代表所有客戶(hù)端
     T AllExcept(params string[] excludeConnectionIds); // 除了參數(shù)中的所有客戶(hù)端
     T Client(string connectionId); // 特定的客戶(hù)端,這個(gè)方法也就是我們實(shí)現(xiàn)端對(duì)端聊天的關(guān)鍵
     T Clients(IList<string> connectionIds); // 參數(shù)中的客戶(hù)端端
     T Group(string groupName, params string[] excludeConnectionIds); // 指定客戶(hù)端組,這個(gè)也是實(shí)現(xiàn)群聊的關(guān)鍵所在
     T Groups(IList<string> groupNames, params string[] excludeConnectionIds);
     T User(string userId); // 特定的用戶(hù)
     T Users(IList<string> userIds); // 參數(shù)中的用戶(hù)
    }
    在SignalR中,每一個(gè)客戶(hù)端為標(biāo)記其唯一性,SignalR都會(huì)分配它一個(gè)ConnnectionId,這樣我們就可以通過(guò)ConnnectionId來(lái)找到特定的客戶(hù)端了。這樣,我們?cè)谙蚰硞€(gè)客戶(hù)端發(fā)送消息的時(shí)候,除了要將消息傳入,也需要將發(fā)送給對(duì)方的ConnectionId輸入,這樣服務(wù)端就能根據(jù)傳入的ConnectionId來(lái)轉(zhuǎn)發(fā)對(duì)應(yīng)的消息給對(duì)應(yīng)的客戶(hù)端了。這樣也就完成了端對(duì)端聊天的功能。另外,如果用戶(hù)如果不在線的話(huà),服務(wù)端可以把消息保存到數(shù)據(jù)庫(kù)中,等對(duì)應(yīng)的客戶(hù)端上線的時(shí)候,再?gòu)臄?shù)據(jù)庫(kù)中查看該客戶(hù)端是否有消息需要推送,有的話(huà),從數(shù)據(jù)庫(kù)取出數(shù)據(jù),將該數(shù)據(jù)推送給該客戶(hù)端。(不過(guò)這點(diǎn),服務(wù)端緩存數(shù)據(jù)的功能本篇博文沒(méi)有實(shí)現(xiàn),在這里介紹就是讓大家明白QQ一個(gè)實(shí)現(xiàn)原理)。
    下面我們來(lái)梳理下端對(duì)端聊天功能的實(shí)現(xiàn)思路:
    客戶(hù)端登入的時(shí)候記錄下客戶(hù)端的ConnnectionId,并將用戶(hù)加入到一個(gè)靜態(tài)數(shù)組中,該數(shù)據(jù)為了記錄所有在線用戶(hù)。
    用戶(hù)可以點(diǎn)擊在線用戶(hù)中的用戶(hù)聊天,在發(fā)送消息的時(shí)候,需要將ConnectionId一并傳入到服務(wù)端。
    服務(wù)端根據(jù)傳入的消息內(nèi)容和ConnectionId調(diào)用Clients.Client(connnection).sendMessage方法來(lái)進(jìn)行轉(zhuǎn)發(fā)到對(duì)應(yīng)的客戶(hù)端。
    三、實(shí)現(xiàn)酷炫聊天功能核心代碼
    有了實(shí)現(xiàn)思路,實(shí)現(xiàn)功能也就得心應(yīng)手了,接下來(lái),讓我們先看下集線器ChatHub中的代碼:
    public class ChatHub : Hub
     {
      // 靜態(tài)屬性
      public static List<UserInfo> OnlineUsers = new List<UserInfo>(); // 在線用戶(hù)列表
      /// <summary>
      /// 登錄連線
      /// </summary>
      /// <param name="userId">用戶(hù)Id</param>
      /// <param name="userName">用戶(hù)名</param>
      public void Connect(string userId, string userName)
      {
       var connnectId = Context.ConnectionId;
       if (OnlineUsers.Count(x => x.ConnectionId == connnectId) == 0)
       {
        if (OnlineUsers.Any(x => x.UserId == userId))
        {
         var items = OnlineUsers.Where(x => x.UserId == userId).ToList();
         foreach (var item in items)
         {
          Clients.AllExcept(connnectId).onUserDisconnected(item.ConnectionId, item.UserName);
         }
         OnlineUsers.RemoveAll(x => x.UserId == userId);
        }
        //添加在線人員
        OnlineUsers.Add(new UserInfo
        {
         ConnectionId = connnectId,
         UserId = userId,
         UserName = userName,
         LastLoginTime = DateTime.Now
        });
       }
       // 所有客戶(hù)端同步在線用戶(hù)
       Clients.All.onConnected(connnectId, userName, OnlineUsers);
      }
      /// <summary>
      /// 發(fā)送私聊
      /// </summary>
      /// <param name="toUserId">接收方用戶(hù)連接ID</param>
      /// <param name="message">內(nèi)容</param>
      public void SendPrivateMessage(string toUserId, string message)
      {
       var fromUserId = Context.ConnectionId;
       var toUser = OnlineUsers.FirstOrDefault(x => x.ConnectionId == toUserId);
       var fromUser = OnlineUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);
       if (toUser != null && fromUser != null)
       { 
        // send to 
        Clients.Client(toUserId).receivePrivateMessage(fromUserId, fromUser.UserName, message);
        // send to caller user
        // Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
       }
       else
       {
        //表示對(duì)方不在線
        Clients.Caller.absentSubscriber();
       }
      }
      /// <summary>
      /// 斷線時(shí)調(diào)用
      /// </summary>
      /// <param name="stopCalled"></param>
      /// <returns></returns>
      public override Task OnDisconnected(bool stopCalled)
      {
       var user = OnlineUsers.FirstOrDefault(u => u.ConnectionId == Context.ConnectionId);
       // 判斷用戶(hù)是否存在,存在則刪除
       if (user == null) return base.OnDisconnected(stopCalled);
       Clients.All.onUserDisconnected(user.ConnectionId, user.UserName); //調(diào)用客戶(hù)端用戶(hù)離線通知
       // 刪除用戶(hù)
       OnlineUsers.Remove(user);
       return base.OnDisconnected(stopCalled);
      }
     }
    上面是服務(wù)端主要的實(shí)現(xiàn),接下來(lái)看看客戶(hù)端的實(shí)現(xiàn)代碼:
    <script type="text/javascript">
     var systemHub = $.connection.chatHub;
     / 連接IM服務(wù)器成功
     // 主要是更新在線用戶(hù)
     systemHub.client.onConnected = function (id, userName, allUsers) {
      var node = chatCore.node, myf = node.list.eq(0), str = '', i = 0;
      myf.addClass('loading');
      onlinenum = allUsers.length;
      if (onlinenum > 0) {
       str += '<li>'
         + '<h5><i></i><span>在線用戶(hù)</span><em>(' + onlinenum + ')</em></h5>'
         + '<ul id="ChatCore_friend_list">';
       for (; i < onlinenum; i++) {
        str += '<li id="userid-' + allUsers[i].UserID + '" data-id="' + allUsers[i].ConnectionId + '" type="one"><img src="/Content/Images/001.jpg?' + allUsers[i].UserID + '"><span>' + allUsers[i].UserName + '(' + ')</span><em>' + allUsers[i].LoginTime + '</em></li>';
       }
       str += '</ul></li>';
       myf.html(str);
      } else {
       myf.html('<li>沒(méi)有任何數(shù)據(jù)</li>');
      }
      myf.removeClass('loading');
     };
     //消息傳輸
    chatCore.transmit = function () {
     var node = chatCore.node, log = {};
     node.sendbtn = $('#ChatCore_sendbtn');
     node.imwrite = $('#ChatCore_write');
     //發(fā)送
     log.send = function () {
      var data = {
       content: node.imwrite.val(),
       id: chatCore.nowchat.id,
       sign_key: '', //密匙
       _: +new Date
      };
      if (data.content.replace(/\s/g, '') === '') {
       layer.tips('說(shuō)點(diǎn)啥唄!', '#ChatCore_write', 2);
       node.imwrite.focus();
      } else {
       //此處皆為模擬
       var keys = chatCore.nowchat.type + chatCore.nowchat.id;
       //聊天模版
       log.html = function (param, type) {
        return '<li>'
         + '<div>'
          + function () {
           if (type === 'me') {
            return '<span>' + param.time + '</span>'
              + '<span>' + param.name + '</span>'
              + '<img src="' + param.face + '" >';
           } else {
            return '<img src="' + param.face + '" >'
              + '<span>' + param.name + '</span>'
              + '<span>' + param.time + '</span>';
           }
          }()
         + '</div>'
         + '<div>' + param.content + '<em></em></div>'
        + '</li>';
       };
       log.imarea = chatCore.chatbox.find('#ChatCore_area' + keys);
       log.imarea.append(log.html({
        time: new Date().toLocaleString(),
        name: config.user.name,
        face: config.user.face,
        content: data.content
       }, 'me'));
       node.imwrite.val('').focus();
       log.imarea.scrollTop(log.imarea[0].scrollHeight);
       // 調(diào)用服務(wù)端sendPrivateMessage方法來(lái)轉(zhuǎn)發(fā)消息
       systemHub.server.sendPrivateMessage(chatCore.nowchat.id, data.content);
      }
     };
     node.sendbtn.on('click', log.send);
     node.imwrite.keyup(function (e) {
      if (e.keyCode === 13) {
       log.send();
      }
     });
    };
     //用戶(hù)離線
     systemHub.client.onUserDisconnected = function (id, userName) {
      onlinenum = onlinenum - 1;
      $(".ChatCore_nums").html("(" + onlinenum + ")");
      $("#ChatCore_friend_list li[data-id=" + id + "]").remove();
     };
     // 啟動(dòng)連接
     $.connection.hub.start().done(function () {
      systemHub.server.connect(userid, username); // 調(diào)用服務(wù)端connect方法
     });
    </script> 
    上面只是列出了一些核心代碼實(shí)現(xiàn)。另外,為了實(shí)現(xiàn)的酷炫的效果,這里采用了一個(gè)Jquery插件:layer,官方網(wǎng)址為:http://layer.layui.com/。這個(gè)插件主要為了實(shí)現(xiàn)彈出框和彈出層的效果,要實(shí)現(xiàn)酷炫的聊天特效,就需要自己寫(xiě)JS代碼了,由于本人并不是很熟悉前端,所以這個(gè)JS特效代碼也是參考網(wǎng)絡(luò)上的實(shí)現(xiàn)。大家如果想運(yùn)行查看效果,建議到文章末尾下載源碼進(jìn)行運(yùn)行。
    四、最終效果
    介紹完了實(shí)現(xiàn)思路和實(shí)現(xiàn)代碼之后,既然就到了我們激動(dòng)人心的一刻了,那就是看看我們實(shí)現(xiàn)功能是否可以滿(mǎn)足需求,另外,除了滿(mǎn)足基本的聊天功能外,還需要看看界面是不是夠酷炫。
    五、總結(jié)
    看完上面的效果,是不是很炫呢。到此,本文的內(nèi)容就結(jié)束了,在接下來(lái)的一篇文章中我會(huì)繼續(xù)介紹如何使用Asp.net SignalR來(lái)實(shí)現(xiàn)聊天室的功能。