18
Introduction to SignalR “Persistent connection” between clients and server in ASP.NET

Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Embed Size (px)

DESCRIPTION

"Persistent connection" between client and server allow you to push data from server to client. The connection between clients and server is persisted over best possible transport mechanism, which could be a combination of periodic polling, long polling and websockets (new html5 specification). In this way transport layer is abstracted to provide a seamless persistent connection. There are two connection models: Hubs (high level) and PersistentConnection (low level) . Client side will be created an ajax / javascript proxy-hub that intercept the callback coming from the server. The proxy-hub will be also used to send calls from client to server. You can also use (for example) SignalR in an ArcGis web map application to create a layer with point coming from some sensor or a windows phone checkin message. You can download the demo code at this link: http://sdrv.ms/RJgdUp There is also a video on YouTube: http://youtu.be/qUG0BQYfmLM

Citation preview

Page 1: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR“Persistent connection” between clients and server in ASP.NET

Page 2: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

Why real-time & how ?

Users want the latest info, NOW !

Page 3: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

Page 4: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

HTTP request/response

It is a unidirectional protocol stateless

Never designed for real-time communications

Where are we ? On the web !

Page 5: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

Page 6: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

HTML5 WebSockets

Extension to HTTPProvide raw sockets over HTTPFull-duplexTraverses proxies

Not every browser supports itNot every proxy server supports itNot every webserver supports itThey are raw sockets !

Page 7: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

SignalR

Create a “persistent connection” between client and server allowing you to push data from server to client.

Abstracts away the transport

Provides just one programming model

Not an official Microsoft project yet

For more details: https://github.com/SignalR/SignalR

Page 8: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

The connection between clients & server is persisted over best possible transport mechanism, which could be a combination of long polling, periodic polling & sockets. In this way transport layer is abstracted to provide a seamless persistent connection

Page 9: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

Two connection models

Hubs (high level)Can communicate with 1..N clientsAbstraction over PersistentConnectionRoute automatically mapped (/signalr/hubs)Can send messages and call methodsSignalR defines the protocol

PersistentConnection (low level)Can communicate with 1..N clientsIs an IHttpHandlerRequires a route to be definedLimited to sending messagesYou define the “protocol”

Page 10: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

<script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script> <script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script> <script src="signalr/hubs" type="text/javascript"></script>

SignalR registers some code to run at application start time that finds all hubs in your application. On the first request to signalr/hubs, the proxy is generated and cached for the lifetime of the application.

If you navigate to signalr/hubs in your browser, you'll see a script that is dynamically generated based on the hubs declared on the server. Each hub on the server will become a property on the client side $.connection.myHub / $.connection.

Page 11: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

$(function () { // Proxy created on the fly var chat = $.connection.hubChat1;

// Declare a function on hub so the server can invoke it chat.addMessage1 = function (message) { $('#messages').append('<li>' + message + '</li>'); };

// Call the chat method on the server $("#broadcast").click(function () { chat.send1($('#msg').val()); });

// Start the connection $.connection.hub.start();});

Hubs (high level)

Page 12: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

public class HubChat1 : Hub { // Call the chat method on the server public void Send1(string message) { // Call the addMessage method on all clients Clients.addMessage1(message); } }

Invoking methods on the Clients property will broadcast that message to all connected clients (see above). But there are some cases where we want to send a message to specific clients. We can use the indexer on the Clients object to specify a connection id.

Clients[Context.ConnectionId].addMessage(data);

Hubs (high level)

Page 13: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

public class PaginaController : Controller{ public ActionResult Index() { return View(); }

public ActionResult Command() { var context = GlobalHost.ConnectionManager.GetHubContext<HubChat1>(); context.Clients.addMessage1(“Hello world”); return null; } }

If you call an action method into the controller, you can also call a javascript callback. To get the context object for a hub, use this method.

GlobalHost.ConnectionManager.GetHubContext<T>()

Hubs (high level)

Page 14: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

DEMO

Page 15: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalRPersistentConnection (low level)

$(function () { var connection = $.connection('/echo');

connection.received(function (data) { $('#messages').append('<li>' + data + '</li>'); });

$("#broadcast").click(function () { connection.send($('#msg').val()); });

connection.start();});

The "PersistentConnection" requires a route to be defined, it is limited to sending messages and you must define the protocol.

Page 16: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalRPersistentConnection (low level)

public class MyEndPoint : PersistentConnection { protected override Task OnConnectedAsync(IRequest request, string connId) { return Connection.Broadcast("Connection " + connectionId + " connected"); }

protected override Task OnReceivedAsync(IRequest request, string connId, string data) { return Connection.Broadcast("Connection " + connectionId+ " sent " + data); }

protected override Task OnDisconnectAsync(string connId) { return Connection.Broadcast("Connection " + connectionId+ " disconncted"); }}

Page 17: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

DEMO

Page 18: Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

Introduction to SignalR

You can download the demo code at this link: http://sdrv.ms/RJgdUp

There is also a video on YouTube: http://youtu.be/qUG0BQYfmLM