SignalR V2

SignalR versión 2 :


 

What is ASP.NET SignalR: ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time. You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same. SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients' browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization. SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. This tutorial introduces SignalR development by showing how to build a simple browser-based chat application. You will add the SignalR library to an empty ASP.NET web application, create a hub class for sending messages to clients, and create an HTML page that lets users send and receive chat messages. For a similar tutorial that shows how to create a chat application in MVC 5 using an MVC view, see Getting Started with SignalR 2 and MVC 5.


Diferences with WebSocket: In IIS8 we introduced a new interface and associated API's to handle Websocket requests. IWebSocketContext.  WebSocket was  introduced in html5.  in order to make use of websocket  we should allow on  IIS8 socket module . One of the limitations to HTTP is that it was designed as a one-directional method of communication. However, many modern web-based applications require more real-time, two-way communications in order to function optimally, that is why we can make use of websocket protocol and his corresponding code to make an application  bi-directional at once. SignalR is a asp.net Library that  uses web sockets when its supported, and consistent client polling hack when it's not, so, it's the way to go.SignalR is now officially part of ASP.NET. I trust that Microsoft will be releasing new Apis  apart from SignalR that will make use of websocket or not . For more information about websocket go here : https://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support , The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with server that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or s and long polling).


Let´s get started with a simple proyect  SignalR in ASP.NET : SignalR simplifies the process of building real-time applications. It includes an ASP.NET server library and a JavaScript client library to make it easier to manage client-server connections and push content updates to clients. You can add the SignalR library to an existing ASP.NET application to gain real-time functionality. The tutorial demonstrates the following SignalR development tasks: Adding the SignalR library to an ASP.NET web application. Creating a hub class to push content to clients. Creating an OWIN startup class to configure the application. Using the SignalR jQuery library in a web page to send messages and display updates from the hub.

*   Create a new  asp.net proyect  in visual studio 2015  using c# as code.

  A  -> Get it on NuGet! Install-Package Microsoft.AspNet.SignalR.

  B ->   Create a class name ChattHub.cs on your proyect and paste the following code:

 

code:

using System;

 

using System.Collections.Generic;

 

using System.Linq;

 

using System.Web;

 

using Microsoft.AspNet.SignalR;

 

namespace SignalRDaniel

 

{

 

public class ChatHub : Hub

 

{

 

public void send(string name , string message)

 

{

 

Clients.All.broadcastMessage(name, message);

 

}

 

}

 

}

 

C ->  And last copy and then paste the following code into your proyect: you shuold créate a Index.html file.

 

.

 

<!DOCTYPE html>

 

<html xmlns="https://www.w3.org/1999/xhtml">

 

<head>

 

<title>chatting demo daniel</title>

 

</head>

 

<body>

 

<input type="text" id="message" />

 

<input type="button" id="sendmessage" value="Send" />

 

<input type="hidden" id="displayname" />

 

<ul id="discussion"></ul>

 

<script src="Scripts/jquery-2.1.4.min.js"></script>

 

<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>

 

<script src="signalr/hubs"></script>

 

<script type="text/javascript">

 

$(function () {

 

var chat = $.connection.chatHub;

 

chat.client.broadcastMessage = function (name, message) {

 

var encodedName = $('<div />').text(name).html();

 

var encodedMesg = $('<div />').text(message).html();

 

$('#discussion').append('<li><strong>' + encodedName + '</strong>:&nbsp;&nbsp' + encodedMesg + '</li>');

 

};

 

$('#displayname').val(prompt('Enter your Name', ""));

 

$('#message').focus();

 

 

$.connection.hub.start().done(function () {

 

$('#sendmessage').click(function () {

 

chat.server.send($('#displayname').val(), $('#message').val());

 

$('#message').val('').focus();

 

});

 

});

 

});

 

 

</script>

 

</body>

 

</HTML>

    .

D ->  remark: make sure on our webconfig file is the assemply dependency  something like this :

 

< assemblyIdentity name="Microsoft.AspNet.SignalR.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />

 

F ->  Now  execute the proyect and you will have to open 2 browser instances  IE and another Brand such as crohme or Firefox. Type a name in both instances get started chatting.

signalr signalr2


Explanation:

SignalR Hubs

 

In the code sample the ChatHub class derives from the Microsoft.AspNet.SignalR.Hub class. Deriving from the Hub class is a useful way to build a SignalR application. You can create public methods on your hub class and then access those methods by calling them from scripts in a web page.

 

In the chat code, clients call the ChatHub.Send method to send a new message. The hub in turn sends the message to all clients by callingClients.All.broadcastMessage.

 

The Send method demonstrates several hub concepts :

Declare public methods on a hub so that clients can call them. Use the Microsoft.AspNet.SignalR.Hub.Clients dynamic property to access all clients connected to this hub.   Call a function on the client (such as the broadcastMessage function) to update clients.

 public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients.
        Clients.All.broadcastMessage(name, message);
    }
}

 

SignalR and jQuery

The HTML page in the code sample shows how to use the SignalR jQuery library to communicate with a SignalR hub. The essential tasks in the code are declaring a proxy to reference the hub, declaring a function that the server can call to push content to clients, and starting a connection to send messages to the hub.

The following code declares a reference to a hub proxy.

 var chat = $.connection.chatHub; 

Note: In JavaScript the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in JavaScript as chatHub.

The following code is how you create a callback function in the script. The hub class on the server calls this function to push content updates to each client. The two lines that HTML encode the content before displaying it are optional and show a simple way to prevent script injection.

     chat.client.broadcastMessage = function (name, message) {
        // Html encode display name and message. 
        var encodedName = $('<div />').text(name).html();
        var encodedMsg = $('<div />').text(message).html();
        // Add the message to the page. 
        $('#discussion').append('<li><strong>' + encodedName
            + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
    }; 

The following code shows how to open a connection with the hub. The code starts the connection and then passes it a function to handle the click event on the Send button in the HTML page.

Note: This approach ensures that the connection is established before the event handler executes.

     $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            // Call the Send method on the hub. 
            chat.server.send($('#displayname').val(), $('#message').val());
            // Clear text box and reset focus for next comment. 
            $('#message').val('').focus();
        });
    });

I leave you here the HTML code commented in each line:

 

<!DOCTYPE html>

<html>

<head>

<title>SignalR Simple Chat</title>

<style type="text/css">

.container {

background-color: #99CCFF;

border: thick solid #808080;

padding: 20px;

margin: 20px;

}

</style>

</head>

<body>

<div class="container">

<input type="text" id="message" />

<input type="button" id="sendmessage" value="Send" />

<input type="hidden" id="displayname" />

<ul id="discussion"></ul>

</div>

<!--Script references. -->

<!--Reference the jQuery library. -->

<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>

<!--Add script to update the page and send messages.-->

<script type="text/javascript">

$(function () {

// Declare a proxy to reference the hub.

var chat = $.connection.chatHub;

// Create a function that the hub can call to broadcast messages.

chat.client.broadcastMessage = function (name, message) {

// Html encode display name and message.

var encodedName = $('<div />').text(name).html();

var encodedMsg = $('<div />').text(message).html();

// Add the message to the page.

$('#discussion').append('<li><strong>' + encodedName

+ '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');

};

// Get the user name and store it to prepend to messages.

$('#displayname').val(prompt('Enter your name:', ''));

// Set initial focus to message input box.

$('#message').focus();

// Start the connection.

$.connection.hub.start().done(function () {

$('#sendmessage').click(function () {

// Call the Send method on the hub.

chat.server.send($('#displayname').val(), $('#message').val());

// Clear text box and reset focus for next comment.

$('#message').val('').focus();

});

});

});

</script>

</body>

</html>

 

 


 

Remark: some useful information was taken from https://signalr.net/  and https://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr by Patrick Fletcher.