Elaborazione del Suono - labinf
Transcript
Elaborazione del Suono - labinf
HTML5 - Messaging Applicazioni Internet Ingegneria Informatica Antonio Servetti Internet Media Group Dip. di Automatica ed Informatica Politecnico di Torino [email protected] http://media.polito.it http://www.polito.it Pull and push messages Pull: with Ajax the client pulls data from the server A number of ways exist to implement "scripted HTTP requests" from the browser to the server • XmlHttpRequest object • <img>, <iframe>, <script> (as a fallback) Push: with Comet the server pushes data to the client Term coined by Alex Russel in "Comet: Low Latency Data for the Browser", 2007 (also called reverse-ajax) HTML5 defines server-sent events HTML 5 - Client-side storage 2 XHR alternatives <img> Has a src property, when set the broser issues an HTTP GET request A script can pass information to the server encoding it in the query string Limits: the server response will always be an image <iframe> The response is returned in an 'invisible' iframe The script can read that element to get the data Limits: subjects to the same origin policy HTML 5 - Client-side storage 3 XHR alternatives <script> Advantage: not subject to the same-origin policy The server response is JSON encoded data that is automatically "executed" when the response is loaded by the browser It is called JSON with padding (JSONP) The server wraps the response data (JSON) in a JS function call that act as a callback when the data is received • handleResponse( • [1, 2, {"buckle": "my shoe"}] • ) HTML 5 - Client-side storage 4 Disadvantages It cannot handle errors gracefully if your web service returns an HTTP return code other than 200 (successful), then the script tag will silently fail Raw service w.r.t. XHR XMLHttpRequest can receive JSON as well as XML, plain text, and HTML (and now XHR2 binary data) It can send and receive individual HTTP headers Can do both HTTP GETs and POSTs It supports both synchronous and asynchronous calls. HTML 5 - Client-side storage 5 XMLHttpRequest Level 2 XMLHttpRequest Level 2 introduces new capabilities cross-origin requests, ad hoc header • Access-Control-Allow-Origin: * uploading progress events support for uploading/downloading binary data. These extensions allow AJAX to work with many File System API, Web Audio API, and WebGL. See also http://www.html5rocks.com/en/tutorials/file/xhr2/ 6 Cross--document messaging Cross 7 Cross--document messaging Cross Cross-document messaging, or web messaging allows documents to communicate with one another across different origins, or source domains Provides a rudimentary level of security ◦ You are supposed to check from whom the message is coming (origin property) Similar messaging interface also for server-sent events and web workers 8 Same origin policy 9 postMessage The postMessage method requires a reference to the Window object of the receiving document to send text plain messages. As a result, messages can be posted to the following: ◦ ◦ ◦ ◦ other frames or iframes within the sender’s window windows the sender explicitly opens through JS calls the parent window of the sender document the window which opened the sender document The message event has the following attributes: ◦ data – the actual content of the incoming message. ◦ origin - the origin of the sender document ◦ source - a reference to the w. object that sent the msg 10 Example: http://10.0.2.2/HTML5/html5demos.com/postmessage.html Registers an event handler for incoming messages from other domains // in http://www.pippo.com window.addEventListener('message', function(e) { if (e.origin == 'http://example.com') { // you've verified the domain the message is coming from, now do something } , false); Sends a message to another domain // in http://example.com var frame = document.getElementById("someIframe").contentWindow; frame.postMessage("Some message", "http://www.pippo.com"); // syntax: otherWindow.postMessage(message, targetOrigin); 11 Example (idem) If document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A var o = document.getElementsByTagName('iframe')[0]; o.contentWindow.postMessage('Hello B','http://documentB.com/'); Script in document B window.addEventListener('message', receiver, false); function receiver(event) { if (event.origin == 'http://documentA.com') { if (event.data == 'Hello B') { event.source.postMessage('Hello A, how are you?', event.origin); } else { alert (event.data); } } } 12 Where is CrossSiteScripting useful? Browser extensions ◦ That act as background pages and must change current window Mashups ◦ Pages downloaded from one domain that must retrieve data from other domains 13 Server--sent events Server Server-sent events Subscription to notifications / messages generated by a server w.r.t long-polling, SSEs are handled directly by the browser Automatic reconnect (reconnection timeout 3s) w.r.t websockets, no special protocol and no need for full-duplex HTML 5 - Client-side storage 15 Comet The client establish (and re-establish as necessary) a connection to the server The server keeps that connection open so that it can send asynchronous messages over it. Each time the server sends a message, it closes the connection, which helps to ensure that the message is properly received by the client. After processing the message, the client immediately establishes a new connection for future messages. Problems: Some browsers limit the number of connections to the same server HTML 5 - Client-side storage 16 JS API Client side EventSource object if (!!window.EventSource) { var source = new EventSource('stream.php'); source.addEventListener('message', function(e) { console.log(e.data); }, false); } Read more on: http://www.html5rocks.com/en/tutorials/eventsource/basics/ HTML 5 - Client-side storage 17 Event stream format Server side plaintext response with Content-Type: text/event-stream "data:" line, followed by your message and „\n‟ “id:” line to keep track of messages (optional) ends with additional "\n“ response.setContentType("text/event-stream"); PrintWriter out = response.getWriter(); out.print("data: {" + messagesSent++ + "}\n\n"); out.flush(); JSON messages data: data: data: data: {\n "msg": "hello world",\n "id": 12345\n }\n\n HTML 5 - Client-side storage source.addEventListener('message', function(e) { var data = JSON.parse(e.data); console.log(data.id, data.msg); }, false); 18 Example http://googlecodesamples.com/html5/sse/sse.html Long-polling Reconnect HTML 5 - Client-side storage 19 Browsers limitations Only the client can initiate the communication Polling can simulate real-time communication Long polling is used to simulate server requests Browser sends a request to the server Server keeps the request open for a set period Server sends the notification to the browser and closes High server load (asynchronous servlets) Server resources Request/response headers overhead Alternative: streaming Server send response as successive chunks of data HTML5 - Websockets Websockets Two-way server-client connection Handled by the browser Shared port with existing HTTP content Traverses firewalls and (aware) proxies IETF Protocol RFC 6455 (Dec. 2011) (ws:// and wss://) W3C API Faster than XHR reduction in unnecessary network traffic and latency http://jsperf.com/websocket-vs-xhr HTML5 - Websockets Websockets API Check: window.WebSocket object Events: onopen, onerror, onmessage, onclose // Create a new WebSocket var mySocket = new WebSocket("ws://www.WebSocket.org"); // Associate listeners mySocket.onmessage = function(evt) { alert("Received message: " + evt.data); }; HTML5 - Websockets Websockets API Functions: send, close Attributes: url, readyState, protocol, extensions, bufferedAmount // Sending data mySocket.send("WebSocket Rocks!"); // Close WebSocket mySocket.close(); HTML5 - Websockets Websocket protocol Starts its life as an HTTP connection, (backwards compatibile) Then switches from HTTP to WebSocket (WebSocket handshake) Upgrade header "Upgrade: websocket" The server, in turn agrees to the protocol switch again through the Upgrade header At this point the HTTP connection breaks down and is replaced by the WebSocket connection over the same underlying TCP/IP connection. HTML5 - Websockets Websocket protocol HTML5 - Websockets Websocket frames Text or binary data Few header bytes (minimally framed) WebSocket text frames use a terminator, while binary frames use a length prefix. In the case of text frames, each frame starts with a 0x00 byte, ends with a 0xFF byte, and contains UTF-8 data in between. Mask (client-to-server) 32-bit value chosen at random by the client. HTML5 - Websockets Websocket frames Wireshark Trace (Client to Server) Text or binary data Few header bytes WebSocket text frames use a terminator, while binary frames use a length prefix. In the case of text frames, each frame starts with a bit, MASKa bit, 0xFF byte, and contains UTF-8 0x00 byte, endsFIN with RSV bits, Op- payload mask payload Code length data in between. 81 85 CB 6E 9F 8E 83 0B F3 E2 A4 Mask (client-to-server) 0B F3 32-bit value chosen at random by the 83 client. XOR CB 6E 9F -- -- -48 65 6C H e l HTML5 - Websockets E2 8E -6C l A4 CB -6F o Proxies HTML5 - Websockets http://www.infoq.com/articles/Web-Sockets-Proxy-Servers Proxies WebSocket protocol is unaware of proxy servers and firewalls HTTP-based handshake Proxy type Connection Outcome Explicit Unencrypted Explicit Encrypted 1. HTTP CONNECT 2. WebSocket connection flows to destination Transparent Unencrypted Proxy strips extra headers, connection fails Transparent Encrypted Connection tunnels past proxy HTML5 - Websockets http://www.infoq.com/articles/Web-Sockets-Proxy-Servers Advantages Any connection can support streaming A single connection for both up- and down-load Not limited to browser clients HTML5 - Websockets Browser support Chrome 4+ Safari 5+ Firefox 4+ Opera 10.7+ Internet Explorer 10+ HTML5 - Websockets Server side support Node.js: Socket.IO Java: Jetty, Tomcat 7.0.27 http://tomcat.apache.org/tomcat-7.0-doc/web-socket-howto.html Python: Tornado, pywebsocket JS Frameworks (browser) Socket.IO HTML5 - Websockets Server side implementation Extend websocket.WebSocketServlet Implement createWebSocketInbound Return an object of type StreamInbound which handles the WebSockets communication public class ChatWebSocketServletextends WebSocketServlet { private final AtomicInteger connectionIds = new AtomicInteger(0); @Override protected StreamInbound createWebSocketInbound(String subProtocol) { return new ChatMessageInbound(connectionIds.incrementAndGet()); } } HTML5 - Websockets Server side implementation MessageInbound manages connections based on simple messages Two methods must be implemented. One for opening of the WebSocket and another to receiving the incoming messages. private final class ChatMessageInbound extends MessageInbound { @Override public void onOpen( WsOutbound outbound ) { // This method is called when a WebSocket has a connection } @Override public void onTextMessage( CharBuffer buffer ) throws IOException { // This method is called when a WebSocket receives a message } } HTML5 - Websockets Server side implementation Chat example private final Set<ChatMessageInbound> connections = new CopyOnWriteArraySet<ChatMessageInbound>(); @Override protected void onTextMessage(CharBuffer message) throws IOException { // Never trust the client String filteredMessage = String.format("%s: %s", nickname, HTMLFilter.filter(message.toString())); broadcast(filteredMessage); } private void broadcast(String message) { for (ChatMessageInbound connection : connections) { try { CharBuffer buffer = CharBuffer.wrap(message); connection.getWsOutbound().writeTextMessage(buffer); } catch (IOException ignore) { /* Ignore */ } } HTML5 - Websockets