SignalR not firing OnDisconnected

signalr onconnected not firing
signalr stop
signalr/connect
signalr abort
signalr ping
signalr architecture
signalr keeps disconnecting
signalr inactivity timeout

The problem: SignalR is not firing OnDisconnected on my webserver. It is very simple, but is not firing. I have tried:

  • Closing browser window
  • Navigating away
  • Reloading
  • Firing stop() on the SignalR-connection from client side.

public override Task OnDisconnected(bool stopCalled) {
    LogUtil.LogInfo("Disconn");
    return base.OnDisconnected(stopCalled);
}

I am using SignalR 2.2.0.0 and OnConnected is working just fine. I have tried recommendations of doing at last one client call to make sure the connection is up and running. I have searched all forums, SO, GIT etc etc and nothing solves my issue.

I had problems with this also, I had to use LongPolling. There also isn't any current example of disconnect/reconnect javascript code I could find.

Here's my code (exclude shoddy html included for completeness):

<hr />

<style>
 table { table-layout: fixed; }
 table th, table td { overflow: hidden; }
</style>

<div id="logs">
    <table id="logTable" class="table">
        <thead>
            <tr>
                <th style="width: 20%">Time</th>
                <th style="width: 5%">Level</th>
                <th>Message</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="/lib/signalr-clientES5-1.0.0-alpha2-final.js" type="text/javascript"></script>
<script type="text/javascript">

    // global refs
    var transportType;
    var logger;
    var loggingHub;
    var loggingConnection;

    function prependLogRow(logEvent) {
        var d = new Date(logEvent.timeStamp); //.ToString("dd/MM H:mm:ss");
        var m = logEvent.message;
        var s = "<tr><td>" + d + "</td><td>" + logEvent.level + "</td><td>" + m + "</td></tr>";
        $("#logTable tbody").prepend(s);

        var rowCount = $('#logTable tr').length;
        if (rowCount > 500) {
            $("#logTable").find("tr:gt(250)").remove();
        }
    };

    function createLogEvent(message) {
        var logEvent = {};
        logEvent.timeStamp = new Date();
        logEvent.level = 'Info';
        logEvent.message = message;
        return logEvent;
    };

    function bindEvents(logger) {

        logger.connection.onclose = (e) => {
            var logEvent = createLogEvent('Logger disconnected. Retrying...');
            prependLogRow(logEvent);
            setTimeout(function () 
            {
                transportType = signalR.TransportType.LongPolling; //;WebSockets
                logger = new signalR.ConsoleLogger(signalR.LogLevel.Trace);
                loggingHub = new signalR.HttpConnection(`https://${document.location.host}/signalr`, { transport: transportType, logger: logger });
                loggingConnection = new signalR.HubConnection(loggingHub, logger);
                bindEvents(loggingConnection);
                var logEvent = createLogEvent('Logger reconnected.');
                prependLogRow(logEvent);
            }, 1000); // Restart connection after a second.
        };

        logger.on('Log', (logEvent) => {
            prependLogRow(logEvent);
        });

        logger.start().catch(err => {
            console.log('connection error');
        });
    };

    $(document).ready(function () {

        transportType = signalR.TransportType.LongPolling; //;WebSockets
        logger = new signalR.ConsoleLogger(signalR.LogLevel.Trace);
        loggingHub = new signalR.HttpConnection(`https://${document.location.host}/signalr`, { transport: transportType, logger: logger });
        loggingConnection = new signalR.HubConnection(loggingHub, logger);

        bindEvents(loggingConnection);

        var logEvent = createLogEvent('Logger loaded. Please wait...');
        prependLogRow(logEvent);
    })
</script>

this code feels wrong, but was the only iteration i could get to work reliably.

Hub.OnDisconnected event not fire with .NET client · Issue #3974 , Client Side Server: localhost Project: Windows Forms Target framework: 4.6.1 SignalR version: Microsoft.AspNet.SignalR.Client 2.2.2 Server  OnDisconnect not firing at consistent times This behavior is by design. When a user attempts to navigate away from a page with an active SignalR connection, the SignalR client will then make a best-effort attempt to notify the server that the client connection will be stopped.

I also had issues with logging in OnDisconnect not functioning correctly. Like you, I figured that the OnDisconnect method was not being invoked.

But it turns out I was assuming that HttpContext.Current was available. (My logger uses it to pull some state information from the session.) When you think about it, expecting a current context doesn't make sense. You are disconnecting, after all! A null pointer exception was being thrown for HttpContext.Current, but I couldn't see it.

Once I removed the dependency on HttpContext.Current, I was able to log disconnects and send out alert emails.

ASP.NET Hub.OnDisconnected not called when .NET client , NET side: public override Task OnDisconnected() Deploy the server app GitHub is home to over 50 million developers working together to SignalR.​HubDispatcher "Error creating Hub", but this error is not seen every time. After turning on the signalr logging I do see the connection being aborted because of a timeout but the OnDisconnected event is never called on the hub. Is this still an issue. I have also tried using the javascript onbeforeunload to manually call disconnect on the hub but this did not work.

In my case, I needed at least one chat.client.broadcast method to make it work ... otherwise, it would fire any other event but OnDisconnected method.

SignalR .net client OnDisconnected event not fired in different , I create a signalR demo, and override the OnDisconnected event in the Hub. In PC1, the event fired ok. However, I moved my demo to PC2, the  In that case, the SignalR connection continues on the client and the Reconnected event is raised. On the first server, OnDisconnected is never executed, and on the new server, OnReconnected is executed although OnConnected was never executed for that client on that server before.

asp.net SignalR OnConnected and OnDisconnected not firing , asp.net SignalR OnConnected and OnDisconnected not firing? It also turns out that on a script you need to define at least one client callback for events to be  However, it is not called if the network connection suddenly drops. For instance, if I unplug the network cable on the client machine, or disable the client's wireless network, or unplug the router, OnDisconnected() will never get called, even after a several minute wait.

Understanding and Handling Connection Lifetime Events in SignalR , The OnReconnected event handler in a SignalR Hub can execute directly after OnConnected but not after OnDisconnected for a given client. SignalR/SignalR#1149 (comment). No, definitely don't do that. You would do something similar to what we do for heartbeats, just send on an interval if you you don't see a message within that interval you abort the connection. but heartbeat handler is not async :( Yes, we should consider changing this.

SignalR OnConnected and OnDisconnected not firing, I'm having trouble with OnConnected and OnDisconnected overrides in my Hub not firing. For replication purposes, I've got a very simple Hub: public class  Are you saying that there's something specific I need to do on the client-side to get (say) OnDisconnected() to fire? I'm not seeing anything that would make me think that just in looking at the demo app or the SignalR source, but happy to be corrected.

Comments
  • I have the same version, but it takes around 40 seconds to disconnect. (The event does fire after 40 seconds.) The reason has something to do with a feature that tries to reconnect to user in case of slow network - I can't remember it well though. Did you wait for sufficient time after closing the browser? Btw, which browser are you using?
  • I have waited up to 30 minutes. Chrome Version 60.0.3112.113
  • I have chrome 60 as well. Closing the tab, reloading it or invoking stop on client should be adequate. Can you post the hub.connect and hub.stop related code? Also, try adding stateChanged event on the client and see its logs, in case something odd is going on.
  • SignalR state changed from: disconnected to: connecting -> SignalR state changed from: connecting to: connected -> onmessage { "msg": "Users online: 2" } -> -> --Pressing reload -> SignalR state changed from: connected to: disconnected -> SignalR state changed from: disconnected to: connecting -> SignalR state changed from: connecting to: connected
  • hmm that is as expected... so doesn't it fire the server event when the state changes to disconnected?