Skip to content

Introduction ASP.NET SignalR (Eng)

The article of today is about a framework very useful in application that need real-time message and your brand main is be simple. I am speaking of the SignalR framework and I am going to do a small introduction.

A of the things that me impressed in this framework is the following text: “ASP.NET SignalR is a new library for ASP.NET that makes it incredibly simple to add real-time web functionality to your applications”. It left me fascinated and was the point main to I study more.

David Fowler and Damian Edwards, which are of team ASP.NET Microsoft, have developed SignalR as a project personal. Today SignalR is part of stack of developed of the Microsoft and is open source. Can SignalR be only to environments Microsoft? No, SignalR was designed to be used to many devices, as mobile (Andorid, IOS, Windows Phone) and web application as Java, PHP and of course ASP.NET.

Once, I needed to create a chat internal of a company and I did not have good results, although it work. The following my chat without real-time message: All messages that the user have to send for other is always saved in database with the user that would have to receive and a field information that this message wasn’t read. In the other side, the person that is destined the receive that message used to stay waiting, because I marked in system to consult the each 2 second to access the database and seek by new messages doesn’t read.

Notice that in text above I said that the part main the system is access the database from time to time. Do you think this scenario correct to a system equal Watsapp, Skype and Gtalk where must to access from time to time the database? Of course not. To resolve this problem is that we use API of delivery real-time message as SignalR.

How it work SignalR?

SignalR hides the details of low-level to that we can have an appearance of always connected between server and client. When I said that SignalR hides details of low-level is because internally it checks the better connection (Websockets, Long Pooling, Forever Frame e etc) between server and client.

How is your installation?

Your installation is easy and you must use the NUGET of the Visual Studio to install. In the first picture below, items found to SignalR through of the NUGET. Let’s install the first item found that will install the server and client part.

Nuget com SignalR

After of installation of the SignalR, the solution will stay like below. In the first picture, the core to creation of the server and in the second picture, the client (JavaScript) to connect with the server.

Referencias do SignalR

Scripts do SignalR

To this first article, we are going to implement the part of connection with server and in the second article, we are going to construct a game and so understand well SignalR.

What we need now is create the server to receive and to deliver the information in real-time for clients.

To create the server we need of a class with the following statement “public class ExemploSignalRHub : Hub“. As you can see, the ExemploSignalRHub class has the base type as Hub, being this responsible by create the SignalR server. Depending of the form of connection between the server and the client, for example Websockets, this class will remain active during all time. However, if the connection type is other, the class not will remain active. As tip never must utilize member of class to store the system state.

In the next code, we can see that in SampleHub class there are two method where your implementation is in the Hub class.

[sourcecode language=”csharp”]

using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;

namespace Web.SignalR
{

public class SampleHub : Hub
{

public override Task OnConnected()
{
return base.OnConnected();
}

public override Task OnDisconnected()
{
return base.OnDisconnected();
}

}
}

[/sourcecode]

The methods OnConnected and OnDisconnected are events triggered by server to inform there is a new user or user disconnected. These methods can be useful in context where you need to save the log of users. As example, I am going to demo a user accessing the system and the SignalR will trigger the OnConnected event. The code below show a view simple to test.

[sourcecode language=”html”]
<h2>Exemplo SignalR</h2>
<span id=”connectionStatus”></span>
<span id=”log”></span>

@section scripts
{
<script type=”text/javascript” src=”/Scripts/jquery-1.10.2.min.js”></script>
<script type=”text/javascript” src=”/Scripts/jquery.signalR-2.0.3.min.js”></script>
<script src=”@Url.Content(“~/signalr/hubs”)”></script>
<script type=”text/javascript”>

var proxy = $.connection.sampleHub;
$.connection.hub.start().done(function () {

$(‘#connectionStatus’).text(‘conectado’);
}).fail(function (e) {

$(‘#connectionStatus’).text(‘não conectado’);
});
</script>
}
[/sourcecode]

Above we have a view very simple where the objective is show a connection with SignalR server. To it work, we need to reference the file Jquey.js, javascript SignalR and the path ~/signalr/hubs (this path is where the SignalR wait by connections of clients of type Hub). The files must follow this order.

Now let’s to work with SignalR client scripts to connect in the server. In case of success or fail, the view will show the result. Let’s use the instruction “$.connection.hub.start()”, where is responsible by try to connect and checks if there was success or fail. Notice that, in case of sucess or fail, we are accessing the span element to notify the user.

An observation very important that I do is that the each new connection with SignalR, it is given a code of connection for the user, an Id in the format GUID, and this remains with user until the disconnection.

We still do not finish, we need to register the routes of the SignalR in initialization of application to user access. The class below is responsible by initialize the configurations of the SignalR. Note the instruction [assembly: OwinStartup(typeof(SampleWebSignalR.Startup))] where must do reference to itself.

[sourcecode language=”csharp”]
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SampleWebSignalR.Startup))]
namespace SampleWebSignalR
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
[/sourcecode]

Done! Now we can execute our solution and validate if is right the connection with SignalR Server. The picture below show the result.

signalr conectado

I am going to improve our example and really use the concept of real-time message. Let’s to implement a function that alert all users when a new user accesses the application informing your connection id. To do this, we need to understand that we must create a JavaScript function that will be responsible by to stay waiting messages of the server and when trigged, must to execute the procedure that we want.

[sourcecode language=”javascript”]
var proxy = $.connection.sampleHub;

proxy.client.entryClient = function (connectionId) {
$(‘#log’).append(‘&amp;amp;amp;lt;br /&amp;amp;amp;gt;Entrada de cliente: ‘ + connectionId);
}

proxy.client.exitClient = function (connectionId) {
$(‘#log’).append(‘&amp;amp;amp;lt;br /&amp;amp;amp;gt;Saida cliente: ‘ + connectionId);
}

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

$(‘#connectionStatus’).text(‘conectado’);

}).fail(function (e) {

$(‘#connectionStatus’).text(‘não conectado’);
});
[/sourcecode]

See that in the first line of the code above, have a variable with name “proxy” that receives the class created in the server. Note that the class created in the server is SampleHub and in the JavaScript is sampleHub. The lowercase letter is because the framework does the conversion in the JavaScript patters.

Now that we have the Hub class of the side JavaScript, we can prepare the functions that are going to stay waiting the server call. Below we have two functions, the first trigged when user accesses the application and the second, trigged when the user leaves the application.

[sourcecode language=”javascript”]
proxy.client.entryClient = function (connectionId) {
$(‘#log’).append(‘Entrada de cliente: ‘ + connectionId);
}

proxy.client.exitClient = function (connectionId) {
$(‘#log’).append(‘Saida cliente: ‘ + connectionId);
}
[/sourcecode]

Note with attention like was created a listening function. See that the proxy variable calls the client property to after of dynamic form calls the client function. How the server could do this access? It is seen in the code below.

[sourcecode language=”javascript”]
public override Task OnConnected()
{
Clients.All.entryClient(Context.ConnectionId);
return base.OnConnected();
}

public override Task OnDisconnected()
{
Clients.All.exitClient(Context.ConnectionId);
return base.OnDisconnected();
}
[/sourcecode]

Do you remember of the methods of events of the SampleHub class? Through them, let’s alert all user the connection Id of the user that accessed or came out the application. To test we have that to open many browsers (simulating users different) and to note the log that the application prints.

signalr log

And here I end the first article and I hope to have helped you understand better the SignalR. Soon I am going to do more article about SignalR involving a most complex example of a game. See you.

www.stephanybatista.com

Published in.Net FrameworkC#Visual Studio

One Comment

  1. marcelo marcelo

    Olá, parabens pelo material !! Tirou diversas dúvidas e me esclareceu muita coisa…
    Uma dúvida me restou…caso eu queira que os usuários estejam sempre conectados, mas nem sempre online, como funciona no whatsapp, aonde eu altero ? Por ex: eu quero que um usuário que nao esteja com o app aberto, receba mensagens… e também ninguem desconecte de determinado grupo… igual whatsapp mesmo.

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *