VueJs SignalR chat application with Dot net core.

If you haven't used signalr in any of your application, Let me give a brief introduction about signalr with an example, In your application dashboard you want to display all the new notification message in realtime. what you will do?
One approach you can do is constantly polling that particular method and check any updates available. 
In this case, you unnecessarily keep calling the backend method to get the information. It affects the performance of your application. here you can use signalr  to provide real-time behavior.

So here I am explaining how we can create a simple chat application using signalr and vuejs.

Pre requisites: Asp.net core
IIS and WebSocket enabled - (windows features > IIS )

Here we are using asp.net core signalr. Its pretty simple and straight forward so I will just add the code part.





Here I have browsed web application in two different browsers to create two chat instances.
(ie & chrome)

You have to create a ChatHub and configure it in the startup class.

So my ChatHub class goes like this.

 public class ChatHub : Hub
    {
        public override Task OnConnectedAsync()
        {
            Console.WriteLine("ChatHub hub connected");
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            Console.WriteLine("ChatHub hub disconnected");
            return base.OnDisconnectedAsync(exception);
        }

        public async Task SendMessage(string user, string message)
        {
            Console.WriteLine("Message received");
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }

So here I am just broadcasting the received message to all subscribing clients.

In ConfigureServices method

  services.AddSignalR();
In the Configure method

  app.UseSignalR(hubRouteBuilder => {
                hubRouteBuilder.MapHub<ChatHub>("/signalr");
         });
add the following codes, bingo your signalr app is ready to use.

Now we will check the web app part. I have created a vuecli app.
There are other 'signalr' packages that compatible to dot net framework. but you need to use the below npm package if you are using dotnet core signalr.

"@aspnet/signalr":"1.1.4"
This package is used in our app for establishing the connection with signalr Hub.
And the component for the same is below. It's straight forward code one method to invoke the signalr part and we are subscribing the data in the mounted hook.

<script lang="ts">
import { Component, Inject, Vue } from 'vue-property-decorator';
import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
import * as signalR from '@aspnet/signalr';
@Component({
  components: {
    HelloWorld,
  },
})
export default class Home extends Vue {

  public user: string = '';
  public message: string = '';
  public listMessage: any = [];
  public  connection = new signalR.HubConnectionBuilder()
    .withUrl('https://localhost:5001/signalr')
    .build();
  public mounted() {
    this.connection.on('ReceiveMessage', (user: string, data: string) => {
           const insertdata = {name: user, message: data};
           this.listMessage.push(insertdata);
           // tslint:disable-next-line:no-console
           console.log(this.listMessage);
           // tslint:disable-next-line:no-console
           console.log(user, data);
     });
  }
  public SignalR() {
    if (this.connection.state === signalR.HubConnectionState.Connected) {
    this.connection.invoke('SendMessage', this.user, this.message);
        } else {
    this.connection.start()
            .then(() => this.connection.invoke('SendMessage', this.user, this.message));
      }
  }

public Clear() {
  this.listMessage = [];
}
}
</script>

Code for the same can be found in my git hub repo.

Youtube version 

0 comments: