public void AddToRoom(string groupName, string userName) { //将连接添加到指定的组(Groups为HubBase中的接口属性) Groups.Add(Context.ConnectionId, groupName); //根据组名称获取对应客户端的组,调用该组的addUserIn方法 Clients.Group(groupName, new string[0]).addUserIn(groupName, userName); } public void Send(string groupName, string detail, string userName) { //Clients.All.addSomeMessage(detail);//群发给所有 //调用客户端某一个组的addSomeMessage Clients.Group(groupName, new string[0]).addSomeMessage(groupName, detail, userName); }
客户端代码
chat.client.addSomeMessage = function(groupId, detail, userName) { console.info("广播消息:" + detail); $("#contentMsg").append("<li>" + userName + ": " + detail + "</li>"); }; chat.client.addUserIn = function(groupId, userName) { $("#contentMsg").append("<li>" + userName + "进入"+groupId+"号聊天室!</li>"); }; $.connection.hub.logging = true; //启动signalr状态功能 $.connection.hub.start().done(function() { //加入聊天室 $("#joinRoom").click(function() { var groupId = $("#groupId").val(); var userName = $("#userName").val(); chat.server.addToRoom(groupId, userName); }); //发送消息 $("#send").click(function() { var detail = $("#message").val(); var groupId = $("#groupId").val(); var userName = $("#userName").val(); chat.server.send(groupId, detail, userName); }); });
运行效果
从上面两张图可以看出,客户端实现了分组