Wednesday, November 11, 2015

SignalR - Simple Implementation.

SignalR is an API Provided by Asp.net used in web applications to build real time push functionalities and "Push" content to the connected clients.

It's very simple and easy to install SignalR in your application by visual studio 2012.

 1: Go to the Visual Studio Tools > NuGet Package Manager > Manage NuGet Package for Solution.

 2: Type SignalR in Search Filed.

 

After installation, you will get these libraries in your Scripts folder.


3: Reference the jQuery library in your webpage.

    <script src="Scripts/jquery-1.6.4.min.js" ></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>

4: Create a C# Class and inherits with Hub Class.

// Server Code.
public class MessageHub : Hub
{
    public void Send(string name, string message)
    {
           Clients.All.broadcastMessage(name, message);
    }
}

Here we have two methods. One is "Send" and other is Client.All.broadcastMessage();
"Send" Method is defined on the Server and will be consumed by client. and broadcastMessage Method will be defined on the client. when the client call the Send Method broadcastMessage will be invoked on the every connected clients.

5: Initialize MessageHub Class on Client.

// Client code.

<script>

var chat = $.connection.messageHub;
chat.client.broadcastMessage = function (name, message) {
              alert(name + " Said: " + message );
     };

  $.connection.hub.start().done(function () {
    $("#btn" ).click(fucntion(){
           chat.server.send("Zeeshan", "Hello All");
    });
    });

</script>

First line; creates a reference of a server MessageHub.cs Class. Make sure it must be in camel case means first latter must be small.

Second line; declares a function on the client which will be invoked by the "Send" Method declared on the Server.

When ever a user visits a webpage which is implemented with SignalR.
 $.connection.hub.start().done(function(){})  event automatically fires and indicate that a new connection is stared.
It takes a function as a parameter in done() function and enable us to call server methods inside it. "Server method must be in camel case on client."

When user will press the button "#btn", the name and message will be broadcast to the all connected users.


This the very simple example, use this code in your own manner.

No comments:

Post a Comment