這篇文章主要為大家詳細(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來實(shí)現(xiàn)類似QQ聊天的功能。
二、使用SignalR實(shí)現(xiàn)端對(duì)端聊天的思路
在介紹具體實(shí)現(xiàn)之前,我先來介紹了使用SignalR實(shí)現(xiàn)端對(duì)端聊天的思路。相信大家在前篇文章已經(jīng)看到過Clients.All.sendMessage(name, message);這樣的代碼,其表示調(diào)用所有客戶端的SendMessage。SignalR的集線器使得客戶端和服務(wù)端可以進(jìn)行實(shí)時(shí)通信。那要實(shí)現(xiàn)端對(duì)端的聊天,自然就不能像所有客戶端發(fā)送消息了,而只能向特定的客戶端發(fā)送消息才可以,不然不就亂套了,沒有任何隱私權(quán)了。那怎樣才可以向特定的客戶端發(fā)送消息呢?這個(gè)問題也就是我們實(shí)現(xiàn)端對(duì)端聊天功能的關(guān)鍵。
我們發(fā)送Clients對(duì)象除了All屬性外,還具有其他屬性,你可以在VS中按F12來查看Clients對(duì)象的所有屬性或方法,具體的定義如下:
public interface IHubConnectionContext<T>
{
T All { get; } // 代表所有客戶端
T AllExcept(params string[] excludeConnectionIds); // 除了參數(shù)中的所有客戶端
T Client(string connectionId); // 特定的客戶端,這個(gè)方法也就是我們實(shí)現(xiàn)端對(duì)端聊天的關(guān)鍵
T Clients(IList<string> connectionIds); // 參數(shù)中的客戶端端
T Group(string groupName, params string[] excludeConnectionIds); // 指定客戶端組,這個(gè)也是實(shí)現(xiàn)群聊的關(guān)鍵所在
T Groups(IList<string> groupNames, params string[] excludeConnectionIds);
T User(string userId); // 特定的用戶
T Users(IList<string> userIds); // 參數(shù)中的用戶
}
在SignalR中,每一個(gè)客戶端為標(biāo)記其唯一性,SignalR都會(huì)分配它一個(gè)ConnnectionId,這樣我們就可以通過ConnnectionId來找到特定的客戶端了。這樣,我們?cè)谙蚰硞€(gè)客戶端發(fā)送消息的時(shí)候,除了要將消息傳入,也需要將發(fā)送給對(duì)方的ConnectionId輸入,這樣服務(wù)端就能根據(jù)傳入的ConnectionId來轉(zhuǎn)發(fā)對(duì)應(yīng)的消息給對(duì)應(yīng)的客戶端了。這樣也就完成了端對(duì)端聊天的功能。另外,如果用戶如果不在線的話,服務(wù)端可以把消息保存到數(shù)據(jù)庫(kù)中,等對(duì)應(yīng)的客戶端上線的時(shí)候,再?gòu)臄?shù)據(jù)庫(kù)中查看該客戶端是否有消息需要推送,有的話,從數(shù)據(jù)庫(kù)取出數(shù)據(jù),將該數(shù)據(jù)推送給該客戶端。(不過這點(diǎn),服務(wù)端緩存數(shù)據(jù)的功能本篇博文沒有實(shí)現(xiàn),在這里介紹就是讓大家明白QQ一個(gè)實(shí)現(xiàn)原理)。
下面我們來梳理下端對(duì)端聊天功能的實(shí)現(xiàn)思路:
客戶端登入的時(shí)候記錄下客戶端的ConnnectionId,并將用戶加入到一個(gè)靜態(tài)數(shù)組中,該數(shù)據(jù)為了記錄所有在線用戶。
用戶可以點(diǎn)擊在線用戶中的用戶聊天,在發(fā)送消息的時(shí)候,需要將ConnectionId一并傳入到服務(wù)端。
服務(wù)端根據(jù)傳入的消息內(nèi)容和ConnectionId調(diào)用Clients.Client(connnection).sendMessage方法來進(jìn)行轉(zhuǎn)發(fā)到對(duì)應(yīng)的客戶端。
三、實(shí)現(xiàn)酷炫聊天功能核心代碼
有了實(shí)現(xiàn)思路,實(shí)現(xiàn)功能也就得心應(yīng)手了,接下來,讓我們先看下集線器ChatHub中的代碼:
public class ChatHub : Hub
{
// 靜態(tài)屬性
public static List<UserInfo> OnlineUsers = new List<UserInfo>(); // 在線用戶列表
/// <summary>
/// 登錄連線
/// </summary>
/// <param name="userId">用戶Id</param>
/// <param name="userName">用戶名</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
});
}
// 所有客戶端同步在線用戶
Clients.All.onConnected(connnectId, userName, OnlineUsers);
}
/// <summary>
/// 發(fā)送私聊
/// </summary>
/// <param name="toUserId">接收方用戶連接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);
// 判斷用戶是否存在,存在則刪除
if (user == null) return base.OnDisconnected(stopCalled);
Clients.All.onUserDisconnected(user.ConnectionId, user.UserName); //調(diào)用客戶端用戶離線通知
// 刪除用戶
OnlineUsers.Remove(user);
return base.OnDisconnected(stopCalled);
}
}
上面是服務(wù)端主要的實(shí)現(xiàn),接下來看看客戶端的實(shí)現(xiàn)代碼:
<script type="text/javascript">
var systemHub = $.connection.chatHub;
/ 連接IM服務(wù)器成功
// 主要是更新在線用戶
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 class="ChatCore_parentnode ChatCore_liston">'
+ '<h5><i></i><span class="ChatCore_parentname">在線用戶</span><em class="ChatCore_nums">(' + onlinenum + ')</em></h5>'
+ '<ul id="ChatCore_friend_list" class="ChatCore_chatlist">';
for (; i < onlinenum; i++) {
str += '<li id="userid-' + allUsers[i].UserID + '" data-id="' + allUsers[i].ConnectionId + '" class="ChatCore_childnode" type="one"><img src="/Content/Images/001.jpg?' + allUsers[i].UserID + '" class="ChatCore_oneface"><span class="ChatCore_onename">' + allUsers[i].UserName + '(' + ')</span><em class="ChatCore_time">' + allUsers[i].LoginTime + '</em></li>';
}
str += '</ul></li>';
myf.html(str);
} else {
myf.html('<li class="ChatCore_errormsg">沒有任何數(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('說點(diǎn)啥唄!', '#ChatCore_write', 2);
node.imwrite.focus();
} else {
//此處皆為模擬
var keys = chatCore.nowchat.type + chatCore.nowchat.id;
//聊天模版
log.html = function (param, type) {
return '<li class="' + (type === 'me' ? 'ChatCore_chateme' : '') + '">'
+ '<div class="ChatCore_chatuser">'
+ function () {
if (type === 'me') {
return '<span class="ChatCore_chattime">' + param.time + '</span>'
+ '<span class="ChatCore_chatname">' + param.name + '</span>'
+ '<img src="' + param.face + '" >';
} else {
return '<img src="' + param.face + '" >'
+ '<span class="ChatCore_chatname">' + param.name + '</span>'
+ '<span class="ChatCore_chattime">' + param.time + '</span>';
}
}()
+ '</div>'
+ '<div class="ChatCore_chatsay">' + param.content + '<em class="ChatCore_zero"></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方法來轉(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();
}
});
};
//用戶離線
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)酷炫的聊天特效,就需要自己寫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)功能是否可以滿足需求,另外,除了滿足基本的聊天功能外,還需要看看界面是不是夠酷炫。
五、總結(jié)
看完上面的效果,是不是很炫呢。到此,本文的內(nèi)容就結(jié)束了,在接下來的一篇文章中我會(huì)繼續(xù)介紹如何使用Asp.net SignalR來實(shí)現(xiàn)聊天室的功能。