John H
John H

Reputation: 242

SignalR Groups: Do not send message back to sender

When I send a message to a signalR group that I am subscribed to, I get the message back!

I do not want this, I want it to send the message to everyone else in the group.

Is this possible? How?

Upvotes: 4

Views: 2377

Answers (2)

tugberk
tugberk

Reputation: 58434

What you can do here is that you can send the ConnectionId to the client and inspect that. For example, the below one is your hub:

[HubName("moveShape")]
public class MoveShapeHub : Hub
{
    public void MoveShape(double x, double y)
    {
        Clients.shapeMoved(Context.ConnectionId, x, y);
    }
}

At the client level, you can do the following:

var hub = $.connection.moveShape,
    $shape = $("#shape"),
    $clientCount = $("#clientCount"),
    body = window.document.body;

$.extend(hub, {
    shapeMoved: function (cid, x, y) {
        if ($.connection.hub.id !== cid) {
            $shape.css({
                left: (body.clientWidth - $shape.width()) * x,
                top: (body.clientHeight - $shape.height()) * y
            });
        }
    }
});

Edit

Starting from SignalR 1.0.0-alpha, there is a built-in API for that if you are using Hubs:

[HubName("moveShape")]
public class MoveShapeHub : Hub
{
    public void MoveShape(double x, double y)
    {
        Clients.Others.shapeMoved(x, y);
    }
}

This will broadcast the data everybody but the Caller.

Upvotes: 5

Ben Clark-Robinson
Ben Clark-Robinson

Reputation: 1459

Now with SignalR you are able to use

Clients.OthersInGroup("foo").send(message);

which does exactly what you're after. It will send a SignalR client message to everyone in a group except the caller.

You can read more here: SignalR wiki Hubs

Upvotes: 5

Related Questions