Is it possible to filter receivers in SignalR?

I ran into the following problem. I would like to do the following. When a new client connects, the group parameter is sent to the SignalR server (by URL or otherwise). Then I want to notify only clients from a specific group.

eg.

I have 3 clients: 1) with group parameter = a 2) with group parameter = a 3) with group parameter = b 

I want to notify only clients with group parameter == a. If I use dynamic field clients, it will send a message to all clients. Is it possible to filter receivers in some way?

+4
source share
2 answers

If you want to send a message to all members of the group, you need to add the client to the group. you can specify the name of the group, or you can let customers choose. For instance:

 <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script> <script src="Scripts/jquery.signalR.js" type="text/javascript"></script> <script src="signalr/hubs" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { var g = $.connection.groups; g.send = function (t) { $("#groups").append(t); }; $("#btnJoin").click(function () { g.addGroup($("#gr").val()); }); $("#btnSend").click(function () { g.sendMessage("a"); //for example a group. }); $.connection.hub.start(); }); </script> <select id="gr"> <option value="a">a</option> <option value="b">b</option> <option value="c">c</option> </select> <div id="groups"></div> <input id="btnJoin" type="button" value="Join"/> <input id="btnSend" type="button" value="Send"/> 

 public class Groups : Hub { public void AddGroup(string groupName) { GroupManager.AddToGroup(Context.ClientId, groupName); Clients.send(Context.ClientId + " join " + groupName + " group.<br />"); } public void SendMessage(string groupName) { Clients[groupName].send(groupName + " group - Hello Everybody!"); } } 
+12
source

The hfor SignalR2 syntax is as follows

Working with groups in SignalR

Example:

 public class ContosoChatHub : Hub { public Task JoinRoom(string roomName) { return Groups.Add(Context.ConnectionId, roomName); } public Task LeaveRoom(string roomName) { return Groups.Remove(Context.ConnectionId, roomName); } } 
0
source

Source: https://habr.com/ru/post/1399779/


All Articles