real time communication with signalr (android client)

38
Real-time Communications with SignalR Deepak Gupta Lead Mobile Developer Email: [email protected] Twitter: @trush_kas

Upload: deepak-gupta

Post on 14-Apr-2017

240 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Real time Communication with Signalr (Android Client)

Real-time Communications with SignalR

Deepak GuptaLead Mobile Developer

Email: [email protected]: @trush_kas

Page 2: Real time Communication with Signalr (Android Client)

Agenda1) Introduction to the real-time web2) ASP.NET SignalR3) Building a real-time4) Implementing Signalr on Android

Page 3: Real time Communication with Signalr (Android Client)

Real-time Application?Real-time functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

Page 4: Real time Communication with Signalr (Android Client)

Client Browser

WebServer

Got Data?Got Data?Got Data?Got Data?

Here’s some data!Got Data?Got Data?Got Data?Got Data?

Without real-time

Page 5: Real time Communication with Signalr (Android Client)

Client Browser

WebServer

I do real time, do you?

Absolutely!

With real-time

Let’s Party in Real-time!

Page 6: Real time Communication with Signalr (Android Client)

Why Real-time?

Users want the latest info, NOW!

Page 7: Real time Communication with Signalr (Android Client)

Show Me Some Examples Twitter, Facebook, Mail - live

searches/updates Stock streamers Auctions Interactive games Live Scores Collaborative apps (google docs, office web

apps) Live user analytics (live graphs)

Page 8: Real time Communication with Signalr (Android Client)

How to do real-time in web?

Page 9: Real time Communication with Signalr (Android Client)

Periodic polling

Poll from time to time using Ajax Delay in communication due to polling

interval Wastes bandwidth & latency

Server

ClientPolling interval

Page 10: Real time Communication with Signalr (Android Client)

Long polling

Poll but doesn’t respond until there's data Poll again after data received or after the

connection times out Consumes server & threads & connection

resources

Server

Client

Page 11: Real time Communication with Signalr (Android Client)

Forever Frame

Server tells client that response is chucked Client keeps connection open until server closes it Server pushed data to the client followed by \0 Consumes server threads

Server

Client

Page 12: Real time Communication with Signalr (Android Client)

HTML5 Web sockets Extension to HTTP Provides raw sockets over HTTP Full-duplex Traverses proxies

It's still a working draft Not every proxy server supports it Not every web server supports it Not every browser supports it They are raw sockets!

Page 13: Real time Communication with Signalr (Android Client)

Server Sent EventIt is supported by all browser who supports HTML5 except Internet Explorer

Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C.

Page 14: Real time Communication with Signalr (Android Client)

Meet SignalR

Page 15: Real time Communication with Signalr (Android Client)

Client Browser

WebServer

Basically…

SignalR!!!

Page 16: Real time Communication with Signalr (Android Client)

Introducing SignalR• SignalR is an asynchronous signalling library for

ASP.Net, to help build real-time multi-user web application.

• SignalR is a compete client and server side solution with JavaScript(jQuery) on client and ASP.Net on the back end to create these kinds of application.

• Abstraction over transports• Events instead of task/async• Connection management• Broadcast or target specific client

Page 17: Real time Communication with Signalr (Android Client)

Picture was taken from http://www.asp.net/signalr

Architecture Diagram

Page 18: Real time Communication with Signalr (Android Client)

What does SignalR do?• Client to Server persistent connection over

HTTP• Easily build multi-user, real-time web

applications• Auto-negotiates transport• Allows server-to-client push and RPC• Built async to scale to 1000’s of connections• Scale out with Service Bus, SQL Server & Redis• Open Source on GitHub

Page 19: Real time Communication with Signalr (Android Client)

SignalR Fallback

Long Polling

Forever Frames

Server Sent Events

Web Sockets

Page 20: Real time Communication with Signalr (Android Client)

SignalR APISignalR provides a simple API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers from server-side .Net code. SignalR package is available by NuGet:

◦ SignalR – A meta package that brings in SignalR.Server and SignalR.Js (this is necessary)

◦ SignalR.Server – Server side components needed to build SignalR endpoints◦ SignalR.Js – Javascript client for SignalR◦ SignalR.Client - .Net client for SignalR◦ SignalR.Ninject – Ninject dependency resolver for SignalR

Page 21: Real time Communication with Signalr (Android Client)

Communication with SignalR

Picture was taken from http://www.asp.net/signalr

Page 22: Real time Communication with Signalr (Android Client)

Server Side – Hub 1/2 Top layer of Persistent Connection Can connect with 1-N clients Can send messages and call methods Routes automatically mapped SignalR handle the binding of complex object and arrays of objects

automatically Communication is serialized by JSON Hubs are per call, which means, each call from client to the hub will create a

new hub instance. Don’t setup static event handlers in hub methods.(3)

Page 23: Real time Communication with Signalr (Android Client)

Server Side – Hub 2/2public class ChatHub : Hub{

public void Send(string name, string message) { //Call the broadcast message method

//to update all clients Clients.All.broadcastMessage(name, message); }}

Page 24: Real time Communication with Signalr (Android Client)

Client Side 1/3<script src="Scripts/jquery-1.8.2.min.js" ></script><script src="Scripts/jquery.signalR-1.0.0.min.js" ></script><script src="/signalr/hubs" ></script> <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) { //Omitted };

//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());

}); }); }); </script>

Page 25: Real time Communication with Signalr (Android Client)

Client Side 2/3Exposing methods from the server - The JavaScript client can declare methods that the server can invoke.

my.Hub.{method} = callback

Method – name of the client side method

Callback – A function to execute when the server invokes the method- If you misspell names you will not get any warnings or notifications even when logging is enabled. On server side is method call hosted on dynamic property (Clients)

Page 26: Real time Communication with Signalr (Android Client)

Client Side 3/3 JavaScript API

◦ $.connection.hub – The connection for all hubs◦ $.connection.hub.id – The client id for the hub connection◦ $.connection.hub.logging – Set to true to enable logging.◦ $.connection.hub.start() – Starts the connection for all hubs.

Page 27: Real time Communication with Signalr (Android Client)

Hub routing Register the route for generated SignalR hubs

◦ Register on server side in Application_Start on global class:public class Global : System.Web.HttpApplication{ protected void Application_Start(object sender, EventArgs e) { //Register the default hubs route: ~/signalr/hubs RouteTable.Routes.MapHubs(); }} Register on client side:<script src="/signalr/hubs" ></script>

Page 28: Real time Communication with Signalr (Android Client)

Some demos Shape move Stock ticker Quiz MavenfyPad Chat

Page 29: Real time Communication with Signalr (Android Client)

What’s it good for? Dashboards Monitoring Collaborative tools Job progress Real-time form Web games Trading Traffic systems, etc.

Page 30: Real time Communication with Signalr (Android Client)

SignalR requirements OS:

◦ Windows Server 2012◦ Windows Server 2008 R2◦ Windows 8/7◦ Windows Azure

IIS – 7/7.5(with Extensionless URL(2)); 8/8 Express .Net – 4.5 framework

Page 31: Real time Communication with Signalr (Android Client)

Signalr implementation onAndroid

Page 32: Real time Communication with Signalr (Android Client)

How it works (1/2)

1. SignalR uses Web Socket and Server Sent Event to push data from server to android devices.

2. It needs signalr library, java web socket, gson (link https://github.com/SignalR/java-client/)

Page 33: Real time Communication with Signalr (Android Client)

How it works (2/2)Include library in your project

Add project dependency in gradle

Page 34: Real time Communication with Signalr (Android Client)

Start ConnectionPlatform.loadPlatformComponent(new AndroidPlatformComponent());mHubConnection = new HubConnection(HOST, "", true, null);mHubProxy = mHubConnection.createHubProxy(HUB_NAME);ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());SignalRFuture<Void> awaitConnection = mHubConnection.start(clientTransport);awaitConnection.done(new Action<Void>() { @Override public void run(Void obj) throws Exception { // Hub Connected }}).onError(new ErrorCallback() { @Override public void onError(Throwable error) { // Connection Error }}).onCancelled(new Runnable() { @Override public void run() { // Connection Canceled }});

Page 35: Real time Communication with Signalr (Android Client)

Subscribe for client method

mHubProxy.on(METHOD_NAME, new SubscriptionHandler3<String, String, String>() { @Override public void run(String param1, String param2, String param3) { // action to perform }}, String.class, String.class, String.class);

mHubProxy.on(METHOD_NAME, new SubscriptionHandler1<String>() { @Override public void run(String param1) { // action to perform }}, String.class);

Page 36: Real time Communication with Signalr (Android Client)

Push data to servermHubProxy.invoke("Send", name, message, time);

Log trace of signalrLogger logger = new Logger() {

@Override public void log(String message, LogLevel level) { Log.d(TAG, message); }};

mHubConnection = new HubConnection(HOST, "", true, logger);

Page 37: Real time Communication with Signalr (Android Client)

Challenges

1. Missing data.2. Connection closed.3. Security issue.

Page 38: Real time Communication with Signalr (Android Client)

References 1.) Comet - http://en.wikipedia.org/wiki/Comet_(programming) 2.) ISS with Extensionless url support – http://

support.microsoft.com/kb/980368 3.) Hub api guide server - http://

www.asp.net/signalr/overview/hubs-api/hubs-api-guide-server 4.) Android Github link - https://github.com/SignalR/java-client/