Use of SignalIR

0

I'm developing a chat in SignalIR, and I can only send the messages to all logged in users, using this way:

public void Send(string name, string message)
{            
    Clients.All.broadcastMessage(name, message);
}

I would like to send to a specific user, how can I do this?

    
asked by anonymous 08.11.2016 / 19:08

1 answer

0

To send a specific user or users, you need to map the user to the connection. There are 4 ways you can do this, among them are:

  • IUserID provider
  • In-memory
  • Single-user groups
  • Database

I'll give you a basic example of mapping a connection using In-memory :

public class ChatHub : Hub
    {
        private readonly static ConnectionMapping<string> _connections = 
            new ConnectionMapping<string>();

        public void Send(string who, string message)
        {
            string name = Context.User.Identity.Name;

            foreach (var connectionId in _connections.GetConnections(who))
            {
                Clients.Client(connectionId).addChatMessage(name + ": " + message);
            }
        }

        public override Task OnConnected()
        {
           //é executado quando a conexão se conecta a esta instância do hub.
        }

        public override Task OnDisconnected(bool stopCalled)
        {
          //é executado quando uma conexão se desconecta desta instância do hub.
        }

        public override Task OnReconnected()
        {
          //é executado quando uma conexão de transporte é automaticamente restabelecida depois de ter sido perdida.
        }
    }

Doc - Mapping SignalR Users to Connections: Here

Doc - Event Handlers: Here

    
07.06.2017 / 07:35