简体   繁体   中英

client specific message by signalR

I am trying to send a message to a SignalR client, but it should not broadcast to all, I went through many article about clientId and groups, but there are no straightforward examples or points given. My client code is below:

proxy: null,

//Getting the connection object
connection = .hubConnection('url')

//Creating proxy
this.proxy = connection.createHubProxy('SignalRServerHub');
this.proxy.on('displayStatus', function (a) {
   SignalRMessageTableService.getDataFromServer()
});

//Starting connection
connection.start()
//we are able to capture connection.id here
//under .done function but not sure how to use

Please let me know step by step solution or any article reference so I can understand it easily.

To respond to a specific client with connectionId you can do something like this:

       var connectionId = Context.ConnectionId;
       Clients.Client(connectionId).someMethod(resultValue);

Or to respond only to the caller:

    Clients.Caller.someMethod(resultValue);

These calls are made from within public methods in your hub class, and do the same.

EDIT:

It looks like the connection.start() should be expanded a bit. You do not need to handle the connectionId, if the server are going to return data or callback to an event at the caller. This will be done by the server, and handled by the methods posted above.

Try changing the connection.start() line to something like this:

connection.start().done(function() {
    $('#someButton').click(function () {
        var param1 = $('#someField').val();
        var param2 = $('#someField2').val();
        this.proxy.invoke('myHubMethod', param1, param2, paramN);
    });
});

Do the neccessary changes to apply this to yout implementation. This code is based on the one you'll find in the documentation. Since it looks like you don't use the generated proxy, we use the invoke method on the proxy to tell which method, and which parameters we are going to send. This also wires up an event to a button with id=someButton , which will fire the myHubMethod on the hub when clicked.

The alternative would be something like (with generated proxy):

this.proxy.server.myHubMethod(param1, param2, paramN);

You should take a look on the ASP.NET SignalR Hubs API Guide - JavaScript Client

If you want to send message to a specific user, you can use the new method in version 2.0

Clients.User(userId).send(message);

by default, the user id used is the IPrincipal.Identity.Name . If you want to override the user id mechanism with your own mapping, refer to this reply - https://stackoverflow.com/a/21355406/2489038

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