Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR doesn't use 'on' subscription after connection to server is started

Tags:

signalr

I have SignalR working with an Angular client, but I can't get proxy.on() to work if the connection is established before I subscribe to events.

My server method invokes the client method pushToClient on both hubs.

var connection1 = $.hubConnection(); //Works fine since I started connection AFTER subscribing
var proxy1 = connection1.createHubProxy('clientPushHub');
proxy1.on('sendToClient', function (message) {
    console.log('This will work: ' + message);
});
connection.start();

var connection2 = $.hubConnection(); // Doesn't work when I start the connection BEFORE subscribing
var proxy2 = connection2.createHubProxy('clientPushHub');
connection2.start();
proxy2.on('sendToClient', function (message) {
    console.log('This will not work: ' + message);
});

If I change things so that proxy2 subscribes to pushToClient before starting connection2, it works fine. Also tried doing the 'on' subscription in the start().done() callback but that did not work.

I've downloaded and verified this example works as I expected when subscribing after connecting, and this ASP.NET article/section specifically mentions you can do things in this order if you don't use a generated proxy, which I haven't.

What worked for the asker in this SO question does not work for me.

Any ideas where I might have gone wrong?

like image 481
wilee Avatar asked Jan 07 '23 10:01

wilee


1 Answers

Based on this post, it sounds like you have to have at least one event listener prior to calling start. From there you can add more event handlers using the 'on' functionality.

EDIT:

Try this.

proxy2.on('foo',function(){});
connection2.start();
proxy2.on('sendToClient', function (message) {
    console.log('This will not work: ' + message);
});

Also this is from the article you linked you for post:

Note: Normally you register event handlers before calling the start method to establish the connection. If you want to register some event handlers after establishing the connection, you can do that, but you must register at least one of your event handler(s) before calling the startmethod. One reason for this is that there can be many Hubs in an application, but you wouldn't want to trigger the OnConnected event on every Hub if you are only going to use to one of them. When the connection is established, the presence of a client method on a Hub's proxy is what tells SignalR to trigger the OnConnected event. If you don't register any event handlers before calling the start method, you will be able to invoke methods on the Hub, but the Hub'sOnConnected method won't be called and no client methods will be invoked from the server.

like image 114
damnnewbie Avatar answered May 19 '23 09:05

damnnewbie