Author : MD TAREQ HASSAN

SignalR Client

Add the SignalR client library

Client JS Code

Create chat.js in wwwroot/js

wwwroot/js/chat.js

"use strict";

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

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

Creating client view

For simplicity, using Razor page (MVC can also be used in the same way)

Pages\Index.cshtml

@page
    <div class="container">
        <div class="row">&nbsp;</div>
        <div class="row">
            <div class="col-2">User</div>
            <div class="col-4"><input type="text" id="userInput" /></div>
        </div>
        <div class="row">
            <div class="col-2">Message</div>
            <div class="col-4"><input type="text" id="messageInput" /></div>
        </div>
        <div class="row">&nbsp;</div>
        <div class="row">
            <div class="col-6">
                <input type="button" id="sendButton" value="Send Message" />
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <hr />
        </div>
    </div>
    <div class="row">
        <div class="col-6">
            <ul id="messagesList"></ul>
        </div>
    </div>
<script src="~/js/signalr/dist/browser/signalr.min.js"></script>
<script src="~/js/chat.js"></script>

Client connection events

wwwroot/js/chat.js

// Initialize the SignalR client
var connection = new signalR.HubConnectionBuilder()
    .withUrl('/chatHub')
    .build();

connection.on('ReceiveMessage', renderMessage);

connection.onclose(function () {
    onDisconnected();
    console.log('Reconnecting in 5 seconds...');
    setTimeout(startConnection, 5000);
})


connection.start()
    .then(onConnected)
    .catch(function (err) {
        console.error(err);
    });


function onConnected() {
    console.log('connected');
}

function onDisconnected() {
    console.log('disconnected');
}

Client console app

Install-Package Microsoft.AspNetCore.SignalR.Client

Program.cs

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("Press a key to start listening..");
		Console.ReadKey();
		var connection = new HubConnectionBuilder()
			.WithUrl("http://localhost:60907/coffeehub")
			.AddMessagePackProtocol()
			.Build();

		connection.On<Order>("NewOrder", (order) => 
			Console.WriteLine($"Somebody ordered an {order.Product}"));

		connection.StartAsync().GetAwaiter().GetResult();

		Console.WriteLine("Listening. Press a key to quit");
		Console.ReadKey();
	}
}

public class Order
{
	public string Product { get; set; }
	public string Size { get; set; }
}