How to allow JavaScript to receive a message sent to a specific user (or self) using Signal R?

I previously asked this question but it was closed for duplication owing to this thread (SignalR – Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*) – but this doesn’t show the JavaScript as made clear in my title.

I have a WebForm application in ASP.Net that uses SignalR to push live data to the user logged in. The setup works perfectly, but realised I am broadcasting messages to all clients, which whilst it doesn’t cause the wrong data to displayed to the logged in user, does cause the JavaScript function to get called for all users when just one has a data push.

I have amended the Hub code to broadcast to a specific user (User) and provided the User ID, and I have also tried Client with a Connection ID. Both fire off fine in the codebehind, but the javascript will not update the front end.

I believe it’s because the JavaScript has not been modified to listen for a message sent to the user, but I’m not sure how I need to adapt the code to allow the message to be received.

The 2 tried lines in Hub here:

context.Clients.User(Me.Context.User.Identity.GetUserId()).ReceiveNotification(notifCount)
context.Clients.Client(Me.Context.ConnectionId).ReceiveNotification(notifCount)

JavaScript/jQuery function for the SignalR message here:

$(function () {
    var nf = $.connection.notificationHub;

    nf.client.receiveNotification = function (notifCount) {
        // Update data
    }

    $.connection.hub.start().done(function () {
        nf.server.sendNotifications();
    }).fail(function (e) {
        alert(e);
    });
    //$.connection.hub.start();
});

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

For calling back to the client (or self) you should use:

Clients.Caller.addContosoChatMessageToPage(name, message);

And for calling users you should use:
Clients.Client(Context.ConnectionId).addContosoChatMessageToPage(name, message);

Reference – docs


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x