Use of the Signalir

Asked

Viewed 142 times

0

I am developing a chat in Signalir, and I can only send 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 ?

  • Are you using Asp ?

  • Yes, if you want I’ll send you the full code

  • I found here at Soen an example that worked for me. http://stackoverflow.com/questions/19522103/signalr-sending-a-message-to-a-specific-user-using-iuseridprovider-new-2-0

  • It didn’t work out here, it’s possible I could use the $.connection.hub.idfor that reason?

  • I use the sign on Asp.net and mobile apps...if the link above does not help me let me know that I help you...

  • @Andreneto, for you to send a specific user, need to map the user’s connection. Please look at the answer. Anything let me know.

Show 1 more comment

1 answer

0

To send a specific user or users, you need to map user to 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 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.