Date post: | 17-Dec-2014 |
Category: |
Technology |
Upload: | christian-wenz |
View: | 246 times |
Download: | 0 times |
www.arrabiata.co.uk
HTML5/JavaScript Communication APIs
Dutch PHP Conference, 27.06.2014
Christian Wenz
Arrabiata Solutions
::As a specialist for digital solutions we offer our clients all services from
conception to realization, support and optimization. Our focus is international
with offices in Munich and London. Arrabiata Solutions was founded in 2006
and has more than 30 employees with a combined experience of over 100
successful projects. ::
Arrabiata is a full-service digital agency.
AGENDA
STATUS QUO
WORKING AROND SOP
MESSAGING API
SSE & WEB SOCKETS
CONCLUSION
Status Quo
• GET requests via anything with an src attribute
– No restrictions
– Only possible to provide URL
• Any (browser-supported) HTTP verb via XMLHttpRequest
– Can set headers and HTTP body
– Restricted by SOP (same-origin policy)• Protocol, domain, port
• Still using HTTP
Working around SOP: JSONP
• JSON with padding
• Ajax call:– <script src="http://domain/file.ashx?jsonp=func">
</script>
• Return value:– func([1, 2, 3]);
• „Padding“ is „func“
• Works in virtually any browser
• Still is kinda hackish
CORS
• Cross-Origin Resource Sharing
• Works around the Same Origin Policy
• Restrictions must be met, though– Specific Content-type header
– Origin header
– Server uses Access-Control-Allow-Origin header(value must be * or Origin header for the browserto proceed)
• Advanced approach: preflighted requests (e.g. for POST requests to avoid CSRF)
Messaging API
• Simple cross-domain mechanism to send/receive data
• Works everywhere except IE7-, and limited in IE8+
• Sending:– Access other window (e.g. contentWindow
property of an iframe)– Use postMessage() method to send data (1st
argument)– For security reasons, use origin of target site as
2nd argument
Messaging API (2)
• Receiving:
– Wait for window‘s message event.
– Event arguments contain the data sent (dataproperty) and the origin of the sender (originproperty)
– Use postMessage() to send data back to theorigin
– Sender may use the message event as well to process the data from the receiver.
Server-Sent Events
• JavaScript API for long polling requests
• Server continously sends data, the client just receives and processes them
• Step 1: subscribe to source
– var es = new EventSource("polling.ext");
• Step 2: listen to message event
– es.onmessage = function(ev) {console.log(ev.data);
};
• Works almost everywhere except IE
Stream Format
• Content-type: text/event-stream
• Fields: id, data, event, retry (all optional!)
• Format: <field>: <value>
• Blank lines between fields
• id: 123data: abc
id: 456event: def
Reconnecting to the Server
• Browser reconnects the connection everyfew seconds (unless changed by retrystream value)
• Browser sends Last-Event-ID HTTP header ifserver sent ID before
• Allows server to only send new events
Web Sockets
• Full duplex communication
• Circumvents a few of the disadvantages ofHTTP (metadata sent with each request, re-establishment of the connection, etc.)
• Works in all recent browsers except IE9-
HTTP Handshake
• Request:GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13Origin: http://example.com
• Response:HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat
API for Web Sockets
• Server: depends on the technology used; node.js is theposter child of the month
• Client: – var w = new WebSocket("ws://server:1234");
– w.onopen = function(ev) {w.send("Hi!");
}
w.onmessage = function(ev) {console.log(ev.data);
}
Websocket Server with node.js
var server = require('http');var webSocketServer = require("websocket").server;
server.listen(1234);
var wsServer = new webSocketServer({httpServer: server
});
wsServer.on('request', function(request) { …
});
Socket.IO
• There are countless protocol versions for Web Sockets
• Better use an abstraction layer that also provides polyfillsfor browsers that use an older API version, e.g. Socket.IO (http://socket.io/).
• Server:– var io = require("socket.io").listen(1234);
• Client:– var ws = io.connect("http://127.0.0.1:1234");
Decision Chart
Technique X-Domain Return data Backchannel Long running High Performance
src
XHR
JSONP
CORS
Messaging
Workers
Server-SentEvents
Web Sockets
Thank You!
• http://www.arrabiata.co.uk/
• @chwenz
• Rate this session: http://joind.in/talk/view/10857