DEV Community

Cover image for How to send client-specific messages using SignalR with automatic reconnection
sabrinasuarezarrieta
sabrinasuarezarrieta

Posted on • Edited on

How to send client-specific messages using SignalR with automatic reconnection

A class in my master made me reflect in the importance to share information that really will be useful for somebody in a simple and easy way to understand it, and now I have the perfect opportunity to do it, This week I had to do a task, I had to integrate a socket connection to a chat, it was needed that the messages will be sent to the specific user to whom it was sent, I knew I will be using SignalR and I started to investigate and I found really helpful articles but none of them had everything that I need it in one place with an easy example to understand, in this article, I will share how I developed my solution with a frontend built-in angular and the backend in c#.

First, you have to implement the respective libraries, I will link them, because in the pages will explain how to install and use them for basics better that I will, so for angular and for c#

SignalR allows messages to be sent to a particular client connection, that's because each client connecting to a SignalR hub has a unique connection id, the first thing that the program should do once is connected is calling a function to obtain that connectionId, like is showing in the example.

connectToWebSocket = () => {
    this.hubConnection = new HubConnectionBuilder().withUrl(url)
      .withAutomaticReconnect()
      .build();
    this.hubConnection 
      .start()
      .then(() => console.log('Connection started!'))
      .then(() => this.getConnectionId())
      .catch(err => console.log('Error while establishing connection :('));
}

public getConnectionId = () => {
    this.hubConnection.invoke('getconnectionid').then(
      (data) => {
        console.log('idConection', data);
        this.saveSocketConnection(data).subscribe(response => {
          console.log('save socket connection works', response);
        });
      }
    );
  }

Through the invoke, you can get the connection to save it, associating it with the user that is logged in your application. As you can see I used .withAutomaticReconnect(), this method can be configured to automatically reconnect the HubConnection, and is really useful because that disconnection can happen for a billion reasons, but every time that the hub reconnects generates a new connectionId and that new id will be provided to the onreconnected callback, that's why I used .onreconnected to get that new id and save it.

this.hubConnection.onreconnected(connectionId => {
      this.getConnectionId()
    });

Now is time to generate the method that will be listening to the backend. in this case, I name the connection broadcastConversationUser but could have any name, and could receive any type of object that you define.

this.hubConnection.on('broadcastConversationUser', (message: Message) => {      
      console.log('broadcastConversation', message);
    });

To send a message from the backend we just need to call the instance of the hub in the project, define the parameter IdSocketConnection as the previously save it connectionId, and name the method the same way you did it in the front, in this case, broadcastConversationUser

public void sendMessage(string idSocketConnection, Message message){
 _hubContext.Clients.Client(idSocketConnection).SendAsync("broadcastConversationUser", message);
}

I hope that this will be useful for someone as it was for me, and good luck.

Top comments (0)