signalr
  1. signalr-handling-disconnects

Handling Disconnects - (SignalR Connection Management)

Syntax

connection.on('disconnected', function() {
    console.log('Disconnected from SignalR server');
});

Example

var connection = new signalR.HubConnectionBuilder().withUrl('/chatHub').build();

connection.start().then(function () {
    console.log('Connected to SignalR server');
}).catch(function (error) {
    console.error(error);
});

connection.on('disconnected', function() {
    console.log('Disconnected from SignalR server');
});

Output

Connected to SignalR server
Disconnected from SignalR server

Explanation

In real-time applications, it is important to handle disconnects as they can occur due to various reasons. SignalR provides a disconnected event that is triggered when the connection is lost between the client and the server.

In the above example, we create a SignalR connection object using the HubConnectionBuilder. We then start the connection using the start method, and on successful connection, we log the message "Connected to SignalR server". We use the on method to listen to the disconnected event and log the message "Disconnected from SignalR server" when the event is triggered.

Use

We can use the disconnected event to handle any disconnects that occur between the client and the server. We can log the disconnect message to the console or perform any other custom action.

Important Points

  • The disconnected event is triggered when the connection between the client and the server is lost.
  • We can use the on method to listen to the disconnected event.
  • We can perform custom actions when the disconnected event is triggered.

Summary

Handling disconnects is an important aspect of real-time applications. In SignalR, we can listen to the disconnected event to handle any disconnects that occur between the client and the server. We can perform custom actions when the disconnected event is triggered.

Published on: