Real-time ASP.NET with SignalR

Post on 19-Jun-2015

7.781 views 3 download

Tags:

Transcript of Real-time ASP.NET with SignalR

Real-time ASP.NET with SignalR

Alex Konduforov

About meLive in KharkovWork at AltexSoftBlogger (merle-amber.blogspot.com)Speaker at different conferences and .NET user groupsKharkov AI club co-organizer

Web evolution

Event-based, real-time UI

Partial page updates (Ajax), RIA

Dynamic pages, forms

Static HTML pages

Users Want the Latest Info

NOW!

Social networks

Auctions

Stock tickers

Web chats

Other applicationsLive scoresReal-time notificationsInteractive gamesCollaborative appsLive user analyticsetc.

Standard solutionsFrequent PollingLong pollingServer-Sent events (HTML5)WebSocket (HTML5)

PollingGet updates frequently using Ajax requests

Pros:---Cons:Delay in resultsWastes bandwidth & latency

Long pollingSimilar to usual polling (Ajax requests)Request waits longer (1-2 minutes)

Pros:Lower load on serverNo delaysCons:Consumes server threads & connection

resources

Server-Sent eventsHTML5, works over HTTPEventSource JavaScript APIContent-type: text/event-stream

Pros:No need to reconnectNo need in a special protocol or server

implementationCons:Works in server-t0-client direction

WebSocketHTML5, new protocol (ws:// and wss://) on

top of TCP

Pros:Full-duplex persistent connection (both ways)Cons:Require Web Socket protocol support on

client (IE10)Require Web Socket protocol support on

server (IIS8)

What to do?

WebSocket Best solution

Not supported on all browsers and server

Server-Sent events + Ajax to send data

Very good Not supported in IE (damn!)

Long Polling Not so good Supported everywhere

Mix Very good Do I need to implement it on my own???

Superman SignalR to the rescue!

Authors

David FowlerDamian Edwards

What is SignalR?Official MS technology to build real-time

multi-user ASP.NET applications: http://signalr.net/

Out-of-box solution that consists of server and client side

Abstraction over the set of transportsOpen-source solution available on GitHub

that can be installed via NuGet

Transports priority

WebSockets

Server-Sent events

Forever Frame (IE hack)

Long Polling

ArchitectureClient side

JS, .NET/WinRT, WP, Silverlight, iOS/Android

Hub API

PersistentConnection API

HubsHigh-level APISimilar to Controller (actions, thread per call)

Supported scenarios

Client calling the serverServer calling clients (all, group, one)State round-tripping between client and

serverBinding complex objects (JSON)Detecting connect, disconnect and reconnect

clientsBroadcasting from outside of a HubAsync scenarios (return Task/Task<T> to

client)

Server calling the clientdynamic Clients propertyJSON serialization

Managing GroupsAdd/remove connections to groups

Broadcasting from outside

Notify clients from another server-side code

JavaScript client$.connection.hub

connection for all hubs (url points to /signalr)

$.connection.hub.id client id for the hub connection

$.connection.hub.start() starts the connection for all hubs

$.connection.{hubname} access a client side hub from the generated proxy

Exposing methods on the clientThe JavaScript client can declare methods

that the server can invoke:

myHub.{method} = callbackdeclares a function the server can invoke.method - name of the client side methodcallback - function to execute when the server

invokes the method

JavaScript example

Asynchronous execution

DEMO

Authentication

Uses ASP.NET authentication mechanismsProvides the Authorize attribute for HubsForms and Windows authenticationsCertificates are available as well

AuthenticationConnection token uniquely identifies clients

SecurityCross-Site Request Forgery (CSRF)

preventionDisable cross domain requestsPass connection token in query string, not

cookieVerify connection token

If authenticated user changes, SignalR requires a re-connection

Configuring SignalRSet in IConfigurationManager:

Settings Description Default value

ConnectionTimeout

amount of time to leave a connection open (110 sec default)

110 seconds

DisconnectTimeout

amount of time to wait after a connection goes away before raising the disconnect event

20 seconds

HeartBeatInterval

interval for checking the state of a connection

10 seconds

KeepAlive amount of time to wait before sending a keep alive packet over an idle connection. Set to null to disable keep alive

30 seconds

SignalR and web farm

Azure Service BusWindows Server Service BusSQL ServerRedis

SignalR over RedisStep 1

Download and install Redis as Windows service

Step 2 Install-Package SignalR.Redis

Step 3

New features in v2.0.NET 4.5 only!iOS and Android support via XamarinPortable .NET clientsSelf hosting packageBackwards compatibility server supportCross domain supportEasier unit testingJavaScript error handlingNew HubException exception

Safe to use?Version 2.0 releasedDynamically evolvingProven and stable technologyUsed in many real-time .NET applicationsOpen-source

Materialshttps://github.com/SignalRhttp://jabbr.nethttp://www.hanselman.com/blog/

CategoryView.aspx?category=SignalRhttp://www.asp.net/signalr/overview/signalr-20http://merle-amber.blogspot.com/2012/11/real-

time-aspnet-signalr.html

Thanks for listening!merle-amber.blogspot.comaikharkov.wordpress.com@konduforov

31337