Skip to content

RagabMohamedRagab/SignalR

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Basic of SignalR

SignalR is library which enable realtime between client and server.


SignalR dependency on request send from clinet to server to response at the same second

SignalR can be useful where :

  • Gaming
  • Social Network
  • Voting
  • GPS
  • Maps
  • Dashboards
  • Travel Alerts
  • Meeting App

RealTime Communication :

SignalR Supports following Techniques for handling realtime.

  • WebScoket
  • Server Send Event
  • logg Polling

Hubs

SignalR used Hubs to Communication Between Client And Server.

Install SignalR in Asp.net core 6

  1. In Solution Explorer, right-click the project, and select Add > Client-Side Library.
  2. In the Add Client-Side Library dialog:
    • Select unpkg for Provider
    • Enter @microsoft/signalr@latest for Library
    • Select Choose specific files, expand the dist/browser folder, and selectsignalr.js and signalr.min.js.
    • Set Target Location to wwwroot/js/signalr/
    • Select Install
 builder.Services.AddSignalR();
 app.MapHub<ChatHub>("/chatHub");

ChatHub Class:

using Microsoft.AspNetCore.SignalR;
namespace Notifcations.Hubs {
    public class ChatHub:Hub {
        // send message to all users
        public async Task SendMessageToAllUsers(string user,string message)
        {
            await Clients.All.SendAsync("ReceiveMessage",user, message);
        }
    }
}

Controller

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Notifcations.Controllers {
    [Authorize(Roles = "User")]
    public class ChattingController : Controller {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Index.cshtml

@{
    ViewData["Title"]="ChatDemo";
}
<section class="d-flex justify-content-between">
    <div class="row w-100">
        <form class="col-md-6 w-100">
            <div class="form-group">
                <label class="form-label">User:</label>
                <input type="text" class="form-control" id="txtUser" required />
            </div>
            <div class="form-group mt-3">
                <label class="form-label">Message:</label>
                <textarea cols="10" rows="10" class="form-control" id="txtMessage" required></textarea>
            </div>
            <div class="from-group mt-3">
                <input type="submit" class="btn btn-primary" id="btnSendMessage" />
            </div>
        </form>
    </div>
    <div class="w-100">
        <div class="row w-100">
            <ul id="messagesList" class="col-md-6" style="list-style-type:none;text-align:start;margin-left: 50px;">
            </ul>
        </div>
    </div>
</section>

Chat.js

"use strict"
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
// Disabled Send button until connections is established
$("#btnSendMessage").prop("disabled", true);
connection.start().then(function () {
    $("#btnSendMessage").prop("disabled", false);
    console.log("Connection is established ChatHub");
}).catch(function (error) {
    return console.error(error.toString());
});
// Funcatinlity Client  to Server
$("#btnSendMessage").click(function (e) {
    var user = $("#txtUser").val();
    var mesg = $("#txtMessage").val();
    // To Server
    connection.invoke("SendMessageToAllUsers", user, mesg).catch(function (erro) {
        return console.error(erro.toString());
    });
    // clear message val
    $("#txtMessage").val('');
    // Focus again 
    $("#txtMessage").focus();
    // clear name
    $("#txtUser").val("");
    e.preventDefault();
});
// Response Server to client
connection.on("ReceiveMessage", function (user, text) {
    var connect = `<br/>${user}:${text}<br/>`;
    $("#messagesList").append(`<li>${connect}</li>`);
});

video....