Establishing Connections with SignalR
Syntax
const connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:5000/chatHub")
.build();
Example
const connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:5000/chatHub")
.build();
// Start the connection.
connection.start().then(() => {
console.log("Connected successfully.");
}).catch((err) => {
console.log("Error connecting to server: " + err);
});
Output
If the connection is established successfully, the console will log "Connected successfully." Otherwise, it will log an error message with the reason why the connection failed.
Explanation
SignalR is a real-time communication library for ASP.NET Core applications. In order to use SignalR, you need to establish a connection between the client and the server. The HubConnectionBuilder
is used to create a connection object that can be used to communicate with the SignalR server.
In the example above, we are creating a connection with a SignalR hub located at http://localhost:5000/chatHub
. The start()
method is used to initiate the connection. If the connection is successful, a Connected
event is triggered.
Use
Establishing connections with SignalR is essential for real-time communication between the client and server. You can use SignalR to build real-time chat applications, multiplayer games, and more.
Important Points
- The
HubConnectionBuilder
is used to create a connection object that can be used to communicate with a SignalR server. - The
withUrl()
method is used to specify the URL of the SignalR hub. - The
start()
method is used to initiate the connection between the client and server. - If the connection is successful, a
Connected
event is triggered.
Summary
In this article, we discussed how to establish connections with SignalR using the HubConnectionBuilder
. We provided a syntax example, demonstrated the output of establishing a successful or unsuccessful connection, explained the use case/application use, and provided important points to remember when working with SignalR.