简体   繁体   中英

Ignoring a client when broadcasting a message with SignalR

I want to ignore the client that made the request to broadcast the message my web app. The only way I can seem to do this is by caching the connectionId of the current user:

public class BroadcastHub : Hub
{

    public override Task OnConnected()
    {
        System.Runtime.Caching.MemoryCache.Default.Set(HttpContext.Current.User.Identity.Name + "-connectionId", Context.ConnectionId, new CacheItemPolicy() { Priority = CacheItemPriority.Default, SlidingExpiration = TimeSpan.FromHours(1), AbsoluteExpiration = MemoryCache.InfiniteAbsoluteExpiration });

        return base.OnConnected();
    }

    public override Task OnReconnected()
    {
        System.Runtime.Caching.MemoryCache.Default.Set(HttpContext.Current.User.Identity.Name + "-connectionId", Context.ConnectionId, new CacheItemPolicy() { Priority = CacheItemPriority.Default, SlidingExpiration = TimeSpan.FromHours(1), AbsoluteExpiration = MemoryCache.InfiniteAbsoluteExpiration });

        return base.OnReconnected();
    }

}

This allows me to do the following in the controller action method:

        IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<BroadcastHub>();
        hubContext.Clients.AllExcept((string)MemoryCache.Default.Get(HttpContext.Current.User.Identity.Name + "-connectionId")).sendAddedPasswordDetail(addedPassword);

This method seems to work... but I'm thinking it might be the wrong way of doing things. Is there a better way to ignore the requesting client?

There is a specific property that allows this particular exception,

hubContext.Clients.Others.YourMethodHere

You can see it used here .

Edit: As per the discussion in the comments, Others is not available when using GlobalHost.ConnectionManager.GetHubContext<T>

You will either need to continue using your current method or find a way to delegate this activity to the BroadcastHub to have access to Others .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM