SignalR: send messages to single client
One of the problems I came across while using SignalR was to send messages to a single client.
In the following example (taken from my game prototype) the static DispatchMessage() is used to send a message to a specific client. Note that the connection id's are generated via the ConnectionFactory explained in my last post (connectionId equals player.Id).
public class ServerHub : Hub { private static readonly IHubContext ctx = GlobalHost.DependencyResolver.Resolve().GetHubContext (); public static void DispatchMessage( int playerId, RpgMessage msg ) { var client = ctx.Clients[playerId.ToString()]; client.serverMessage( msg ); } // other instance method omitted ... }
Here we cache the hub context in a static member. The context exposes a collection of all known clients that we use to get the desired client. Also note that the client.serverMessage() function is implemented on the client side and you should invoke it as a new task rather than in a blocking manner.
Oh, very Weel!
ReplyDeletedude ... you could send me a simple hub ... where I have a few users connected, and I can select them to send an individual message? You would be asking too much? It would be of great help, I am Brazilian and I am very interested in learning how to use SignalR ...
Already very grateful!
Why don't you just take a look at the official wiki: https://github.com/SignalR/SignalR/wiki
DeleteThere you can find examples for everything!