Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR(Hub) can send a message except signal maker?

I'm studying SingalR(https://github.com/SignalR/SignalR).

I'm really want to send a message to all connection except the person who makes a event.

For example,

In Chatting application, there is three client(A,B,C).

Client A type a message, "Hello" and clikc submit.

Clients.addMessage(data); send "Hello" to All Cleint(include cleint A)

I want to send "Hello" only Client B and C.

How can I achieve it?

// I think this can get all Clients, right?
var clients = Hub.GetClients<Chat>();
like image 731
Stonpid Avatar asked Dec 08 '11 10:12

Stonpid


People also ask

How does SignalR hub work?

What is a SignalR hub. The SignalR Hubs API enables you to call methods on connected clients from the server. In the server code, you define methods that are called by client. In the client code, you define methods that are called from the server.

Is SignalR asynchronous?

SignalR is an asynchronous signaling library for ASP.NET that our team is working on to help build real-time multi-user web application.


2 Answers

There's no way to filter message on the server today, but you can block messages to the caller from the client side. If you look at some of the samples on signalr, you'll see that they assign each client a generated id to the client in a method (usually called join). Whenever you invoke a method from the hub, pass the id of the calling client, then on the client side do a check to make sure the id of the client isn't the same as the caller. e.g.

public class Chat : Hub { 
    public void Join() {
        // Assign the caller and id
        Caller.id = Guid.NewGuid().ToString();
    }

    public void DoSomething() {
        // Pass the caller's id back to the client along with any extra data
        Clients.doIt(Caller.id, "value");
    }
}

Client side

var chat = $.connection.chat;
chat.doIt = function(id, value) {
   if(chat.id === id) {
      // The id is the same so do nothing
      return;
   }

   // Otherwise do it!
   alert(value);
};

Hope that helps.

like image 177
davidfowl Avatar answered Sep 18 '22 21:09

davidfowl


It is now (v1.0.0) possible by using Clients.Others property in your Hub.

E.g.: Clients.Others.addMessage(data) calls the method addMessage on all clients except the caller.

like image 35
Zsolt Avatar answered Sep 20 '22 21:09

Zsolt