ex4 群組聊天
http://amani.test.ntpc.edu.tw/signalr/ex/ex4.html
本節重點:
* 將某人加入群組:Groups.Add(id, 群組名稱)
* 將某人退出群組:Groups.Remove(id, 群組名稱)
* 呼叫某一群組Client的函式:Clients.Group(群組名稱)
- 聊天室要傳群組訊息,完整Server端及Client端流程如下:
- Server端ChatHub.cs完整程式碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
//宣告靜態類別,儲存user清單
public static class Users
{
public static Dictionary<string, string> ConnectionIds = new Dictionary<string, string>();
}
//儲存上一個加入的群組
public static string OriginGroup = string.Empty;
//加群組(只能在一個群組)
public Task JoinOnlyOneGroup(string groupId)
{
Groups.Remove(Context.ConnectionId, OriginGroup);
OriginGroup = groupId;
return Groups.Add(Context.ConnectionId, groupId);
}
//加群組(可多個群組)
public Task JoinGroup(string groupId)
{
OriginGroup = groupId;
return Groups.Add(Context.ConnectionId, groupId);
}
//退群組
public Task LeaveGroup(string groupId)
{
return Groups.Remove(Context.ConnectionId, groupId);
}
//傳送訊息給群組
public void SendGroup(string groupId, string message)
{
var user = Users.ConnectionIds.Where(u => u.Key == Context.ConnectionId).FirstOrDefault();
Clients.Group(groupId).show(user.Value + "說:" + message);
}
//傳送訊息給所有User
public void Send(string message)
{
var user = Users.ConnectionIds.Where(u => u.Key == Context.ConnectionId).FirstOrDefault();
Clients.All.show(user.Value + "說:" + message);
}
//傳送訊息給某人
public void SendOne(string id, string message)
{
var from = Users.ConnectionIds.Where(u => u.Key == Context.ConnectionId).FirstOrDefault();
Clients.Client(id).show("<span style='color:red'>" + from.Value + "密你:" + message + "</span>");
}
//新使用者連線進入聊天室
public void userConnected(string name)
{
//將目前使用者新增至user清單
Users.ConnectionIds.Add(Context.ConnectionId,name);
//發送給所有人,取得user清單
Clients.All.getList(Users.ConnectionIds.Select(u => new { id=u.Key,name=u.Value}).ToList());
//通知其他人,有新使用者
Clients.Others.show("歡迎" + name + "進入聊天室");
}
//當使用者斷線時呼叫
//stopCalled是SignalR 2.1.0版新增的參數
public override Task OnDisconnected(bool stopCalled)
{
Clients.Others.removeList(Context.ConnectionId);
Users.ConnectionIds.Remove(Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
}
- Client端index.html完整程式碼:
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalR/hubs"></script>
</head>
<body>
<script>
var chat = $.connection.chatHub;//chatHub小寫
var name = "";
//初始
$(function () {
//name = window.prompt("請輸入姓名:");
name = Math.floor(Math.random() * 10000 + 1) + "用戶";
});
//signalR啟動完成後,要執行的動作
$.connection.hub.start().done(function () {
//通知Server,有新使用者連進來
chat.server.userConnected(name);
//預設進入大廳
chat.server.joinGroup("001");
//按傳送鈕
$('#btnSend').click(function () {
//send();
sendGroup();
});
//按Enter鍵
$('#txtMsg').keydown(function (e) {
if (e.which == 13) {
//send();
sendGroup();
}
});
//選取某一個聊天房
$('#lstGroup li').click(function () {
//改群組的顯示名稱
var name = $(this).html();
var id = $(this).attr('id');
$('#lblGroup').html(name);
$('#lblGroupId').html(id);
//通知Server加入群組
chat.server.joinOnlyOneGroup(id);
});
});
//顯示訊息
chat.client.show = function (message) {
$('#chatRoom').append('<li>' + message + '</li>');
};
//顯示user清單
chat.client.getList = function (users) {
var li = "<li id=all>所有人</li>";
$.each(users, function (i, user) {
li += '<li id='+user.id+' >' +user.name+ '</li>'
});
$('#lstUser').html(li);
};
//使用者離開
chat.client.removeList = function (id) {
$('#' + id).remove();
};
function sendGroup() {
var id = $('#lblGroupId').text();
var message = $('#txtMsg').val();
chat.server.sendGroup(id,message);
$('#txtMsg').val('');
}
</script>
<div style="width:700px;">
<div style="float: left; overflow: scroll; width: 200px; height: 300px">
<p>聊天房</p>
<ul id="lstGroup">
<li id="001">大廳</li>
<li id="002"><span style="background-color:orange;color:white;">橘館</span></li>
<li id="003"><span style="background-color: purple; color: white;">紫館</span></li>
</ul>
</div>
<div style="float: left; overflow: scroll; width: 300px; height: 300px">
<p>聊天室</p>
<ul id="chatRoom"></ul>
</div>
<div style="float: left; overflow: scroll; width: 200px; height: 300px">
<p>使用者列表</p>
<ul id="lstUser">
</ul>
</div>
<div>
<label id="lblGroup">大廳</label>
<label id="lblGroupId" hidden>001</label>
<label id="lblTalkToWho">所有人</label>
<label id="lblTalkToWhoId" hidden>all</label>
<input id="txtMsg" type="text" />
<input id="btnSend" type="button" value="傳送" />
</div>
</div>
</body>
</html>