Reputation: 63966
I realize that these questions are similar:
SignalR - Broadcast to all clients except Caller
Send a message to all clients in a Group, except for the current client
However, they are old and nothing in the current documentation gave me any clues as to whether I am doing the right thing or not.
Here's the question/problem:
I need to be able to broadcast a message from the server-side to all connected clients except the guy that submitted the http request - imagine someone submitting a form and getting all people connected to the same form being notified that something has been submitted.
The way I am doing that now is something like this:
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
var connectionID = HttpContext.Request.Cookies["conn-id"].Value;
context.Clients.AllExcept(connectionID).addMessage(message);
And every time a connection is established, I set ConnectionID in a cookie on the client side as so:
$.connection.hub.start().done(function(){
$.cookie("conn-id",$.connection.hub.id);
});
So my questions are:
Is this the best/only approach I can take in this case? Can I read the connection id of the client that originated the request from somewhere else like hub.Context.ConnectionID
or something similar to the way you would get the SessionID
from HttpContext.Current.Session.SessionID?
Can I set the connection id programmatically when a client connects by setting it to the SessionID, for example? Could that cause a problem for some reason? If so, can you please explain how to set the connection ID programmatically and to which event do I need to hook up in order to do this?
I noticed that everytime the page is reloaded, the connection id is changed to a different guid. How do you set the ConnectionId only once and maintain it at least for the life of the Session?
Upvotes: 30
Views: 26914
Reputation: 18301
Your approach does work, however the correct approach is to use the built in API: Clients.Others.addMessage(message)
. Also there's no need to get the hub context inside the hub itself. You can always access the current connection ID via Context.ConnectionId or send message sto clients via Clients.All.foo();
And you cannot set the ConnectinoID programatically. If you'd like to track users across pages maintain a list of users on your server and then just re-assign the connection id's as they navigate through the site.
Here's a post explaining the tracking of users: SignalR 1.0 beta connection factory
Upvotes: 39
Reputation: 284
If you're sending the message in a method on the Hub class, you can also use Clients.Others to exclude the calling client. You only need to use AllExcept(id) if you're not in a hub method.
See the following for details:
http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-server#selectingclients
Upvotes: 4