SlideShare a Scribd company logo
How to Give Your Sencha App
Real-time Web Performance
James Schreuder
James Schreuder
Principal Software Engineer
www.schreuder.com.au
3
Sencha Touch 2.4
(Cordova)
Web Application
(ExtJS 5)
VM Server
(Azure C# .NET)
Pump Controllers
(Embedded C++/Linux)
Agenda
• Part 1: Data Transfer over the Web
• Part 2: Real-time Data Transfer over the Web
• Part 3: Real-time Web Frameworks and Sencha
• Part 4: Real-time Web over Wireless Networks
Part 1:
Data Transfer over the Web
HTTP 1.0/1.1
Server Client
Request (GET / POST)
Response
- Each HTTP request results in a new TCP socket connection
- Request sent, processed and the response returned within same TCP socket
- Half-duplex communication
- Requests to Web Server are stateless
- Client is required to initiate communication with the Web Server
HTTP Polling: Non Real-time
Server Client
DataUpdates“Sent”
Request
Response
startHttpPolling(url, interval, request) {
setInterval(function(){
Ext.Ajax.request({
url: url,
method: 'POST',
params: { request: request },
success: function(response, opts) {
var dataUpdate = response.responseText;
updateGui(dataUpdate);
},
failure: function(response, opts) {
// error!
}
dataType: "json"});
}, interval);
},
DataUpdatesReceived
1
1
2
3
4
23 23
4 4
1
GET / HTTP/1.1
Host: www.schreuder.com.au
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,
image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8
HTTP/1.1 200 OK
X-Powered-By: PHP/5.6.21
Content-Type: text/html; charset=UTF-8
Date: Tue, 16 Aug 2016 01:12:52 GMT
Accept-Ranges: bytes
Server: LiteSpeed
Connection: Keep-Alive
Content-length: 6286
HTTP 1.1 Request/Response Example
• Header = 200+ bytes
• Not counting the body
GET Request
GET Response
Server Client
• Header = 360+ bytes
HTTP Long Polling: Near Real-time
Server Client
1
2
3
4
DataUpdates“Sent” startHttpLongPoll: function(url, request, timeout) {
var ajaxId = Ext.Ajax.request({
url: url,
method: 'POST',
params: { request : request },
success: function(xhr, opts) {
var dataUpdate = response.responseText;
updateGui(dataUpdate);
startHttpLongPoll(url, request, timeout);
},
failure: function(response, opts){
// error!
},
useDefaultXhrHeader : false,
timeout: timeout
});
},
2
4
1
3
DataUpdatesReceived
1
3
2
4
HTTP Polling: Disadvantages
• HTTP data transfer is inherently half-duplex
• Large data overhead in HTTP Headers
• HTTP Polling:
- New data updates are only available when polled
- Need to balance polling frequency versus the data update arrival
• HTTP Long Polling:
- Better than HTTP Polling as data updates are polled when they become available
- New Long Poll request generated as each update arrives
Part 2:
Real-time Data Transfer over
the Web
Web Sockets (RFC6455 – December 2011)
• TCP Socket initiated from client browser
• Minimal connection handshake
• Small message header overhead (between 6 and 14 bytes)
• Full-duplex and Bi-directional
- Following connection handshake, either client or server can initiate communication
- Both client and server can communicate concurrently
• As close to real-time as the TCP protocol can be
Web Sockets: “Now” Real-time
Server Client
1
2
3
4
DataUpdatesSent
connect: function(url) {
var ws = new WebSocket(“ws://url”);
ws.onopen = function(e) {
// ws open!
};
ws.onclose = function(e) {
// ws closed!
};
ws.onmessage = function(e) {
updateGui(e.message);
}
ws.onerror = function(e) {
// ws error!
};
};
2
4
1
3
DataUpdatesReceived
1
3
2
4
Connect
Connected
Web Sockets (RFC6455): Line Protocol
HTTP Client Request (approx 560 bytes)
1. Connection Handshake
GET ws://www.yourdomain.com:80/ HTTP/1.1
Host: yourdomain.com:7200
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://www.yourdomain.com
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116
Safari/537.36
Accept-Encoding: gzip, deflate, sdch
...(abbreviated)…
HTTP Server Response (approx 120 bytes)
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: Ni3JjfWz9DjUSdDSVnQBJrpk24M=
WS Request
WS Response
Web Sockets (RFC6455): Line Protocol
2. Messaging
Opcode Length
Extended
Length
Mask Data
2 bytes 0/2/8 bytes 4 bytes
(client only)
N bytes
3. Closing Handshake
• Sends close opcode
Message: Header Body
Message: Header Body
WebSockets (RFC6455): API
• Constructor:
- WebSocket(url, optionalProtocol)
• Methods/Properties
- send(s)
- close()
- readyState (CONNECTING, OPEN,
CLOSING, CLOSED)
• Event Handlers
- onopen(e), onclose(e)
- onmessage(e)
- onerror(e)
var ws = new WebSocket(“ws://websocket.org”);
// or: var ws = new WebSocket(“ws://websocket.org:8888”, “ianaProtocolName”);
ws.onopen = function (e) {
console.log(“ws open…”);
};
ws.onclose = function (e) {
console.log(“ws closed…”);
};
ws.onmessage = function (e) {
console.log(“ws message received…”);
if (e.message == “pong”) {
ws.close();
}
};
ws.onerror = function (e) {
console.log(“ws error”, e);
};
if (ws.readyState == “OPEN”) {
ws.send(“ping”);
}
Web Sockets: Browser Version Support
• PC Browsers
- Chrome – 29 and above
- Firefox – 47 and above
- IE –10 and above
- Safari – 9.1 and above
• Device Browsers
- Android Browser – 4.4 and above
- Chrome for Android – 51 and above
- IOS Safari – 9.2 and above (iPhone 4/IOS4 has
a buggy implementation)
- IE for Mobile – Windows Phone 8 and above
• Check:
- https://websocketstest.com/
- http://caniuse.com/#feat=websockets
Demo
Part 3:
Real-time Web Frameworks
and Sencha
Real-time Web Framework Recipes
1. CIY (Code It Yourself):
- Client
• JavaScript Web Sockets
• Fallback to Long Polling when required
- Server
• Node.js / node-js-websocket
• (.NET) SuperSocket and SuperWebSocket
2. Complete frameworks with Web Socket
fallback options:
- SignalR
- socket.io/node.js
SignalR
http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr
SignalR Features
• Transports with Fallbacks:
1. WebSocket
2. Server Sent Events
3. AJAX Long Polling
• Rules
• WebSockets are only be used when:
- Client and server support them
- For cross-domain connections, client needs to support CORS
• JSONP uses Long Polling
SignalR
• Server framework deployable as:
- ASP.NET Web Application
- Standalone executable (eg Windows Service)
- Azure “Web Role” or “Worker Role”
• Scaleout using Azure Service Bus
• https://www.asp.net/signalr/overview/performance/scaleout-with-windows-azure-service-bus
• Client framework should be included as a Sencha Resource:
- SignalR script dependencies
- Hubs file
SignalR C# Hub and Sencha Controller
public class SensorHub : Hub
{
public Sensor getSensor(string id) {
return new Sensor { id = id, name = "Sensor " + id, value = 0.0 };
}
public void notify(Sensor sensor) {
// Notify all clients…
Clients.All.notifySensorUpdate(sensor);
}
Ext.define(‘SignalrClient.controller.SensorController', {
extend: 'Ext.app.Controller',
// config etc…
connectSignalR: function(button, e, eOpts) {
var sensorHub = $.connection.sensorHub;
sensorHub.url = "http://yourdomain.com:8088/signalr";
sensorHub.client.notifySensorUpdate = function (sensor) {
// Code to update Sensor gauges...
};
$.connection.hub.start().done(function () {
// Code to show connection status...
});
var sensor1 = sensorHub.server.getSensor('1');
},
Server C# Classes Client Sencha Controller
SignalR C# Hub and Sencha Controller
public void updateSensor(Sensor sensor) {
// Update local Sensor in persistent store…
notify (sensor)
}
}
public class Sensor
{
public string id { get; set; }
public string name { get; set; }
public double value { get; set; }
}
updateSensor: function(sensorHub, sensor) {
sensorHub.server.updateSensor(sensor);
}
loadSensors: function(sensorHub) {
var sensor1 = sensorHub.server.getSensor('1');
var sensor2 = sensorHub.server.getSensor('2');
var sensor3 = sensorHub.server.getSensor('3');
// Code to add sensors to Store...
}
});
Server C# Classes Client Sencha Controller
Part 4:
Real-time Web over Wireless
Networks
Wireless Network Characteristics
- Bandwidth is typically consistent if you are stationary
- But, bandwidth availability changes rapidly depending upon:
• Obstructions between you and the nearest transmitter/receiver
• Distance from the transmitter/receiver and number of users
LAN Wireless
t
B
t
B
100Mbps
50Kbps
Bandwidth Profiles
Web Sockets to the Rescue?
• Full-duplex communication
• Minimal header size overhead
• “Now” Real-time
But…
• Web Server must allocate resources and maintain state for each WebSocket
• TCP is Stream Oriented – everything will be delivered in order
TCP and Real-time Communication
237 6
High Bandwidth
5 4 1
Low Bandwidth
4 35 2 167
ClientServer
Wireless Simulation
• 10 data updates per second
• 30% packet loss introduced (using “Clumsy”) on Ethernet connection
Delivering the TCP Stream
• Non time-critical data
- Wait!
• Time-critical data
- Throttle data update frequency according to bandwidth availability
- How?
• Consider a request/response mechanism similar to Long Polling, but over Web Sockets
• In other words: “Server, please send me the latest update when you receive this request”
Request/Response Algorithm
DataUpdatesProduced 4
5
6
1
2
3
3
3
7
7
78
9
10
11
12
13
14
10
10
13 13
DataUpdatesReceived
Server Client
Wireless Simulation
• Using a simple request/response algorithm over Web Sockets
• Average latency of each data update is reduced
Application Design Tips
• Prioritize the “real-time-ness” of data
- Give priority to what the user is currently looking at
- Give lower priority to keeping background stores etc up to date
• Register/de-register from data updates as the user navigates an app
• But remember users don’t want to switch to a new screen with old data on it
Application Testing Tips
• Measure your app’s bandwidth usage
• Test your application with:
- Simulated packet loss
- Socket disconnects
• SignalR offers a “connectionSlow” event
• Web Sockets can be queried for their “bufferedAmount”
• High frequency updates consume CPU on devices
• Watch the battery usage on small devices.
Summary
In Summary
• Use of Real-time web makes a highly responsive Sencha app
• Real-time web frameworks are easy to integrate into Sencha
• Web Sockets are great! But remember:
- WebSockets require state and resources to be maintained on Server
- TCP is a stream oriented protocol – everything will be delivered in order
• Test your application under poor network conditions
- Packet loss, disconnects, jitter
• Design your data update algorithm to suit your applications requirements
SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James Schreuder
Demo download:
www.schreuder.com.au/senchacon2016
Backup Slides
SignalR Hubs JavaScript Code
proxies['sensorHub'] = this.createHubProxy('sensorHub');
proxies['sensorHub'].client = { };
proxies['sensorHub'].server = {
getSensor: function (id) {
return proxies['sensorHub'].invoke.apply(proxies['sensorHub'], $.merge(["getSensor"], $.makeArray(arguments)));
},
notify: function (sensor) {
return proxies['sensorHub'].invoke.apply(proxies['sensorHub'], $.merge(["notify"], $.makeArray(arguments)));
}
};
Available from: http://yourdomain:8088/signalr/hubs
Web Sockets: Debugging in Chrome

More Related Content

PPTX
ECS19 - Ingo Gegenwarth - Running Exchange in large environment
PPTX
Building Scalable .NET Web Applications
PPTX
SenchaCon 2016: How Sencha Test Helps Automate Functional Testing of Ext JS M...
PPTX
ASP.NET Core 1.0
PPT
Alpha Five v10.NEW APPLICATION SERVER. CODELESS AJAX
PDF
(ATS6-PLAT09) Deploying Applications on load balanced AEP servers for high av...
PPTX
Introduction to ASP.NET 5
PPTX
Asp.NET Handlers and Modules
ECS19 - Ingo Gegenwarth - Running Exchange in large environment
Building Scalable .NET Web Applications
SenchaCon 2016: How Sencha Test Helps Automate Functional Testing of Ext JS M...
ASP.NET Core 1.0
Alpha Five v10.NEW APPLICATION SERVER. CODELESS AJAX
(ATS6-PLAT09) Deploying Applications on load balanced AEP servers for high av...
Introduction to ASP.NET 5
Asp.NET Handlers and Modules

What's hot (20)

PPTX
Windows Server AppFabric Caching - What it is & when you should use it?
PPTX
Altitude SF 2017: Security at the edge
PPTX
Qui Quaerit, Reperit. AWS Elasticsearch in Action
PPTX
Web Servers(IIS, NGINX, APACHE)
PPTX
Learning ASP.NET 5 and MVC 6
PPT
Web Servers (ppt)
PPTX
App fabric introduction
PPTX
Mule 4 vanrish
PDF
[Struyf] Automate Your Tasks With Azure Functions
PPT
Building An Application For Windows Azure And Sql Azure
PDF
Scale Apache with Nginx
PPTX
Windows Azure Workflows Manager - Running Durable Workflows in the Cloud and ...
PPTX
MVC 6 - the new unified Web programming model
PPTX
ASP.NET vNext
PPTX
Web Server - Internet Applications
PPTX
ASP.NET: Present and future
PPTX
SPCA2013 - Developing SharePoint 2013 Apps with Visual Studio 2012
PPTX
Serverless Computing With Azure Functions
PPT
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
ODP
Developing Microservices using Spring - Beginner's Guide
Windows Server AppFabric Caching - What it is & when you should use it?
Altitude SF 2017: Security at the edge
Qui Quaerit, Reperit. AWS Elasticsearch in Action
Web Servers(IIS, NGINX, APACHE)
Learning ASP.NET 5 and MVC 6
Web Servers (ppt)
App fabric introduction
Mule 4 vanrish
[Struyf] Automate Your Tasks With Azure Functions
Building An Application For Windows Azure And Sql Azure
Scale Apache with Nginx
Windows Azure Workflows Manager - Running Durable Workflows in the Cloud and ...
MVC 6 - the new unified Web programming model
ASP.NET vNext
Web Server - Internet Applications
ASP.NET: Present and future
SPCA2013 - Developing SharePoint 2013 Apps with Visual Studio 2012
Serverless Computing With Azure Functions
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
Developing Microservices using Spring - Beginner's Guide
Ad

Viewers also liked (20)

PPTX
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
PPTX
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
PPT
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
PPTX
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...
PPTX
SenchaCon 2016: Turbocharge your Ext JS App - Per Minborg, Anselm McClain, Jo...
PPTX
SenchaCon 2016: Creating a Flexible and Usable Industry Specific Solution - D...
PPTX
SenchaCon 2016: Refine Enterprise Applications by Focusing on U0ser Experienc...
PPTX
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
PPTX
SenchaCon 2016: Mobile First? Desktop First? Or Should you Think Universal Ap...
PPTX
SenchaCon 2016: Integrating Geospatial Maps & Big Data Using CartoDB via Ext ...
PPTX
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
PPTX
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
PPTX
SenchaCon 2016: JavaScript is Great but Stop Writing It - Rory Hardy
PPT
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
PPTX
Ext JS Architecture Best Practices - Mitchell Simeons
PPT
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
PPTX
Building Ext JS Using HATEOAS - Jeff Stano
PPTX
SenchaCon 2016: Accessibility, Teamwork & Ext JS: A Customer Success Story - ...
PPTX
SenchaCon 2016: Using Ext JS 6 for Cross-Platform Development on Mobile - And...
PPTX
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...
SenchaCon 2016: Turbocharge your Ext JS App - Per Minborg, Anselm McClain, Jo...
SenchaCon 2016: Creating a Flexible and Usable Industry Specific Solution - D...
SenchaCon 2016: Refine Enterprise Applications by Focusing on U0ser Experienc...
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
SenchaCon 2016: Mobile First? Desktop First? Or Should you Think Universal Ap...
SenchaCon 2016: Integrating Geospatial Maps & Big Data Using CartoDB via Ext ...
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
SenchaCon 2016: JavaScript is Great but Stop Writing It - Rory Hardy
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
Ext JS Architecture Best Practices - Mitchell Simeons
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
Building Ext JS Using HATEOAS - Jeff Stano
SenchaCon 2016: Accessibility, Teamwork & Ext JS: A Customer Success Story - ...
SenchaCon 2016: Using Ext JS 6 for Cross-Platform Development on Mobile - And...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
Ad

Similar to SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James Schreuder (20)

PPTX
Basic understanding of websocket and and REST API
PPTX
Building real-time-collaborative-web-applications
PPTX
Webinar slides "Building Real-Time Collaborative Web Applications"
PPTX
Web Socket
PDF
Websocket
PPTX
SignalR Overview
PDF
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
PPT
PPTX
signalr
PPSX
SignalR With ASP.Net part1
PPTX
Real time Communication with Signalr (Android Client)
PPTX
Real-time Communications with SignalR
PDF
sockets SMTP Bmsce ppt information science and engineering
PPTX
Best practices of building data streaming API
PDF
Introduction to SignalR
PPTX
Difference between Client Polling vs Server Push vs Websocket vs Long Polling
PPTX
Server Push Technology ( Ratchet )
PPTX
.NET Conf 2022 - Networking in .NET 7
PPT
java networking
PDF
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
Basic understanding of websocket and and REST API
Building real-time-collaborative-web-applications
Webinar slides "Building Real-Time Collaborative Web Applications"
Web Socket
Websocket
SignalR Overview
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
signalr
SignalR With ASP.Net part1
Real time Communication with Signalr (Android Client)
Real-time Communications with SignalR
sockets SMTP Bmsce ppt information science and engineering
Best practices of building data streaming API
Introduction to SignalR
Difference between Client Polling vs Server Push vs Websocket vs Long Polling
Server Push Technology ( Ratchet )
.NET Conf 2022 - Networking in .NET 7
java networking
IT2255 Web Essentials - Unit V Servlets and Database Connectivity

More from Sencha (14)

PDF
Breathe New Life into Your Existing JavaScript Applications with Web Components
PDF
Ext JS 6.6 Highlights
PDF
Sencha Roadshow 2017: BufferedStore Internals featuring eyeworkers interactiv...
PDF
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
PDF
Sencha Roadshow 2017: Best Practices for Implementing Continuous Web App Testing
PDF
Sencha Roadshow 2017: What's New in Sencha Test
PDF
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
PDF
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
PDF
Sencha Roadshow 2017: Sencha Best Practices: Coworkee App
PDF
Sencha Roadshow 2017: Mobile First or Desktop First
PDF
Sencha Roadshow 2017: Innovations in Ext JS 6.5 and Beyond
PDF
Leveraging React and GraphQL to Create a Performant, Scalable Data Grid
PDF
Learn Key Insights from The State of Web Application Testing Research Report
PPTX
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
Breathe New Life into Your Existing JavaScript Applications with Web Components
Ext JS 6.6 Highlights
Sencha Roadshow 2017: BufferedStore Internals featuring eyeworkers interactiv...
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Best Practices for Implementing Continuous Web App Testing
Sencha Roadshow 2017: What's New in Sencha Test
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Sencha Best Practices: Coworkee App
Sencha Roadshow 2017: Mobile First or Desktop First
Sencha Roadshow 2017: Innovations in Ext JS 6.5 and Beyond
Leveraging React and GraphQL to Create a Performant, Scalable Data Grid
Learn Key Insights from The State of Web Application Testing Research Report
Introducing ExtReact: Adding Powerful Sencha Components to React Apps

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PDF
Approach and Philosophy of On baking technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
MYSQL Presentation for SQL database connectivity
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Machine learning based COVID-19 study performance prediction
Approach and Philosophy of On baking technology
Spectral efficient network and resource selection model in 5G networks
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Empathic Computing: Creating Shared Understanding
Understanding_Digital_Forensics_Presentation.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation_ Review paper, used for researhc scholars
MYSQL Presentation for SQL database connectivity
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...

SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James Schreuder

  • 1. How to Give Your Sencha App Real-time Web Performance James Schreuder
  • 2. James Schreuder Principal Software Engineer www.schreuder.com.au
  • 3. 3 Sencha Touch 2.4 (Cordova) Web Application (ExtJS 5) VM Server (Azure C# .NET) Pump Controllers (Embedded C++/Linux)
  • 4. Agenda • Part 1: Data Transfer over the Web • Part 2: Real-time Data Transfer over the Web • Part 3: Real-time Web Frameworks and Sencha • Part 4: Real-time Web over Wireless Networks
  • 5. Part 1: Data Transfer over the Web
  • 6. HTTP 1.0/1.1 Server Client Request (GET / POST) Response - Each HTTP request results in a new TCP socket connection - Request sent, processed and the response returned within same TCP socket - Half-duplex communication - Requests to Web Server are stateless - Client is required to initiate communication with the Web Server
  • 7. HTTP Polling: Non Real-time Server Client DataUpdates“Sent” Request Response startHttpPolling(url, interval, request) { setInterval(function(){ Ext.Ajax.request({ url: url, method: 'POST', params: { request: request }, success: function(response, opts) { var dataUpdate = response.responseText; updateGui(dataUpdate); }, failure: function(response, opts) { // error! } dataType: "json"}); }, interval); }, DataUpdatesReceived 1 1 2 3 4 23 23 4 4 1
  • 8. GET / HTTP/1.1 Host: www.schreuder.com.au Connection: keep-alive Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9, image/webp,*/*;q=0.8 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8 HTTP/1.1 200 OK X-Powered-By: PHP/5.6.21 Content-Type: text/html; charset=UTF-8 Date: Tue, 16 Aug 2016 01:12:52 GMT Accept-Ranges: bytes Server: LiteSpeed Connection: Keep-Alive Content-length: 6286 HTTP 1.1 Request/Response Example • Header = 200+ bytes • Not counting the body GET Request GET Response Server Client • Header = 360+ bytes
  • 9. HTTP Long Polling: Near Real-time Server Client 1 2 3 4 DataUpdates“Sent” startHttpLongPoll: function(url, request, timeout) { var ajaxId = Ext.Ajax.request({ url: url, method: 'POST', params: { request : request }, success: function(xhr, opts) { var dataUpdate = response.responseText; updateGui(dataUpdate); startHttpLongPoll(url, request, timeout); }, failure: function(response, opts){ // error! }, useDefaultXhrHeader : false, timeout: timeout }); }, 2 4 1 3 DataUpdatesReceived 1 3 2 4
  • 10. HTTP Polling: Disadvantages • HTTP data transfer is inherently half-duplex • Large data overhead in HTTP Headers • HTTP Polling: - New data updates are only available when polled - Need to balance polling frequency versus the data update arrival • HTTP Long Polling: - Better than HTTP Polling as data updates are polled when they become available - New Long Poll request generated as each update arrives
  • 11. Part 2: Real-time Data Transfer over the Web
  • 12. Web Sockets (RFC6455 – December 2011) • TCP Socket initiated from client browser • Minimal connection handshake • Small message header overhead (between 6 and 14 bytes) • Full-duplex and Bi-directional - Following connection handshake, either client or server can initiate communication - Both client and server can communicate concurrently • As close to real-time as the TCP protocol can be
  • 13. Web Sockets: “Now” Real-time Server Client 1 2 3 4 DataUpdatesSent connect: function(url) { var ws = new WebSocket(“ws://url”); ws.onopen = function(e) { // ws open! }; ws.onclose = function(e) { // ws closed! }; ws.onmessage = function(e) { updateGui(e.message); } ws.onerror = function(e) { // ws error! }; }; 2 4 1 3 DataUpdatesReceived 1 3 2 4 Connect Connected
  • 14. Web Sockets (RFC6455): Line Protocol HTTP Client Request (approx 560 bytes) 1. Connection Handshake GET ws://www.yourdomain.com:80/ HTTP/1.1 Host: yourdomain.com:7200 Connection: Upgrade Pragma: no-cache Cache-Control: no-cache Upgrade: websocket Origin: http://www.yourdomain.com Sec-WebSocket-Version: 13 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Accept-Encoding: gzip, deflate, sdch ...(abbreviated)… HTTP Server Response (approx 120 bytes) HTTP/1.1 101 Switching Protocols Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Accept: Ni3JjfWz9DjUSdDSVnQBJrpk24M= WS Request WS Response
  • 15. Web Sockets (RFC6455): Line Protocol 2. Messaging Opcode Length Extended Length Mask Data 2 bytes 0/2/8 bytes 4 bytes (client only) N bytes 3. Closing Handshake • Sends close opcode Message: Header Body Message: Header Body
  • 16. WebSockets (RFC6455): API • Constructor: - WebSocket(url, optionalProtocol) • Methods/Properties - send(s) - close() - readyState (CONNECTING, OPEN, CLOSING, CLOSED) • Event Handlers - onopen(e), onclose(e) - onmessage(e) - onerror(e) var ws = new WebSocket(“ws://websocket.org”); // or: var ws = new WebSocket(“ws://websocket.org:8888”, “ianaProtocolName”); ws.onopen = function (e) { console.log(“ws open…”); }; ws.onclose = function (e) { console.log(“ws closed…”); }; ws.onmessage = function (e) { console.log(“ws message received…”); if (e.message == “pong”) { ws.close(); } }; ws.onerror = function (e) { console.log(“ws error”, e); }; if (ws.readyState == “OPEN”) { ws.send(“ping”); }
  • 17. Web Sockets: Browser Version Support • PC Browsers - Chrome – 29 and above - Firefox – 47 and above - IE –10 and above - Safari – 9.1 and above • Device Browsers - Android Browser – 4.4 and above - Chrome for Android – 51 and above - IOS Safari – 9.2 and above (iPhone 4/IOS4 has a buggy implementation) - IE for Mobile – Windows Phone 8 and above • Check: - https://websocketstest.com/ - http://caniuse.com/#feat=websockets
  • 18. Demo
  • 19. Part 3: Real-time Web Frameworks and Sencha
  • 20. Real-time Web Framework Recipes 1. CIY (Code It Yourself): - Client • JavaScript Web Sockets • Fallback to Long Polling when required - Server • Node.js / node-js-websocket • (.NET) SuperSocket and SuperWebSocket 2. Complete frameworks with Web Socket fallback options: - SignalR - socket.io/node.js
  • 22. SignalR Features • Transports with Fallbacks: 1. WebSocket 2. Server Sent Events 3. AJAX Long Polling • Rules • WebSockets are only be used when: - Client and server support them - For cross-domain connections, client needs to support CORS • JSONP uses Long Polling
  • 23. SignalR • Server framework deployable as: - ASP.NET Web Application - Standalone executable (eg Windows Service) - Azure “Web Role” or “Worker Role” • Scaleout using Azure Service Bus • https://www.asp.net/signalr/overview/performance/scaleout-with-windows-azure-service-bus • Client framework should be included as a Sencha Resource: - SignalR script dependencies - Hubs file
  • 24. SignalR C# Hub and Sencha Controller public class SensorHub : Hub { public Sensor getSensor(string id) { return new Sensor { id = id, name = "Sensor " + id, value = 0.0 }; } public void notify(Sensor sensor) { // Notify all clients… Clients.All.notifySensorUpdate(sensor); } Ext.define(‘SignalrClient.controller.SensorController', { extend: 'Ext.app.Controller', // config etc… connectSignalR: function(button, e, eOpts) { var sensorHub = $.connection.sensorHub; sensorHub.url = "http://yourdomain.com:8088/signalr"; sensorHub.client.notifySensorUpdate = function (sensor) { // Code to update Sensor gauges... }; $.connection.hub.start().done(function () { // Code to show connection status... }); var sensor1 = sensorHub.server.getSensor('1'); }, Server C# Classes Client Sencha Controller
  • 25. SignalR C# Hub and Sencha Controller public void updateSensor(Sensor sensor) { // Update local Sensor in persistent store… notify (sensor) } } public class Sensor { public string id { get; set; } public string name { get; set; } public double value { get; set; } } updateSensor: function(sensorHub, sensor) { sensorHub.server.updateSensor(sensor); } loadSensors: function(sensorHub) { var sensor1 = sensorHub.server.getSensor('1'); var sensor2 = sensorHub.server.getSensor('2'); var sensor3 = sensorHub.server.getSensor('3'); // Code to add sensors to Store... } }); Server C# Classes Client Sencha Controller
  • 26. Part 4: Real-time Web over Wireless Networks
  • 27. Wireless Network Characteristics - Bandwidth is typically consistent if you are stationary - But, bandwidth availability changes rapidly depending upon: • Obstructions between you and the nearest transmitter/receiver • Distance from the transmitter/receiver and number of users LAN Wireless t B t B 100Mbps 50Kbps Bandwidth Profiles
  • 28. Web Sockets to the Rescue? • Full-duplex communication • Minimal header size overhead • “Now” Real-time But… • Web Server must allocate resources and maintain state for each WebSocket • TCP is Stream Oriented – everything will be delivered in order
  • 29. TCP and Real-time Communication 237 6 High Bandwidth 5 4 1 Low Bandwidth 4 35 2 167 ClientServer
  • 30. Wireless Simulation • 10 data updates per second • 30% packet loss introduced (using “Clumsy”) on Ethernet connection
  • 31. Delivering the TCP Stream • Non time-critical data - Wait! • Time-critical data - Throttle data update frequency according to bandwidth availability - How? • Consider a request/response mechanism similar to Long Polling, but over Web Sockets • In other words: “Server, please send me the latest update when you receive this request”
  • 33. Wireless Simulation • Using a simple request/response algorithm over Web Sockets • Average latency of each data update is reduced
  • 34. Application Design Tips • Prioritize the “real-time-ness” of data - Give priority to what the user is currently looking at - Give lower priority to keeping background stores etc up to date • Register/de-register from data updates as the user navigates an app • But remember users don’t want to switch to a new screen with old data on it
  • 35. Application Testing Tips • Measure your app’s bandwidth usage • Test your application with: - Simulated packet loss - Socket disconnects • SignalR offers a “connectionSlow” event • Web Sockets can be queried for their “bufferedAmount” • High frequency updates consume CPU on devices • Watch the battery usage on small devices.
  • 37. In Summary • Use of Real-time web makes a highly responsive Sencha app • Real-time web frameworks are easy to integrate into Sencha • Web Sockets are great! But remember: - WebSockets require state and resources to be maintained on Server - TCP is a stream oriented protocol – everything will be delivered in order • Test your application under poor network conditions - Packet loss, disconnects, jitter • Design your data update algorithm to suit your applications requirements
  • 41. SignalR Hubs JavaScript Code proxies['sensorHub'] = this.createHubProxy('sensorHub'); proxies['sensorHub'].client = { }; proxies['sensorHub'].server = { getSensor: function (id) { return proxies['sensorHub'].invoke.apply(proxies['sensorHub'], $.merge(["getSensor"], $.makeArray(arguments))); }, notify: function (sensor) { return proxies['sensorHub'].invoke.apply(proxies['sensorHub'], $.merge(["notify"], $.makeArray(arguments))); } }; Available from: http://yourdomain:8088/signalr/hubs

Editor's Notes

  • #3: 5 minutes to end of this slide
  • #4: - IoT System Architecture
  • #5: 5 minutes to end of this slide
  • #7: How to poll Good if you know exact interval of message delivery
  • #8: Jitter introduced by polling
  • #9: 9 Minutes
  • #10: How to poll Good if you know exact interval of message delivery
  • #12: 13 minutes
  • #17: 18 Minut
  • #18: 19 minutes
  • #19: 2 minutes on Demo
  • #20: 25 minutes
  • #21: 28 minutes to end of this slide
  • #24: 33 Minutes to end of this slide
  • #26: 37 minutes to end of slide
  • #27: 35 minutes
  • #30: 41 minutes to end of this slide
  • #31: 43 minutes to end of this slide
  • #36: 47 minutes to end of this slide
  • #38: 45 minutes to end of this slide
  • #42: 33 minutes
  • #43: 24 minutes to end of this slide