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.

Comments

  1. Oh, very Weel!

    dude ... 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!

    ReplyDelete
    Replies
    1. Why don't you just take a look at the official wiki: https://github.com/SignalR/SignalR/wiki
      There you can find examples for everything!

      Delete

Post a Comment

Popular posts from this blog

SignalR: Wire-up the ConnectionId with a user instance

Manipulating connection strings