Upgrade to Pro — share decks privately, control downloads, hide ads and more …

HTML5 WebSocket & The Internet of Things in real time - IOT Mad

HTML5 WebSocket & The Internet of Things in real time - IOT Mad

Julio Galarón

March 31, 2012
Tweet

More Decks by Julio Galarón

Other Decks in Technology

Transcript

  1.  ", ("10 Desde la irrupción de AJAX (c.2005), hemos

    usado toda especie de técnicas para hacer frente al problema de comunicación en tiempo real entre navegadores y servidores web. La web se ha construido alrededor del paradigma de HTTP llamado request/response. Un cliente carga una web y nada ocurre hasta que hace click en algún link. Alrededor de 2005 aparece AJAX (Asynchronous JavaScript And XML), permitiendo una comunicación asíncrona con el servidor en segundo plano. De esta forma es posible realizar cambios sobre las páginas sin necesidad de recargarlas y hacer que parezcan más dinámicas. Aun así la comunicación siempre es iniciada por el cliente, la cual requiere de la interacción del usuario, o de un polling periódico para solicitar nuevos datos al servidor. Desde hace tiempo han existido distintas tecnologías para permitir al servidor enviar datos al cliente cuando estos estuviesen disponibles (Push, Comet, Flash sockets, XHR multipart, htmlfiles). De todas formas, todos estos métodos comparten el mismo problema: generan mucho overhead (se envía mucha información en las cabeceras HTTP), el cual no es muy conveniente para aplicaciones en las que se necesite tener una latencia baja.
  2. &*" *0 *0  *0 *0  *0 ,))&+$ "/3"/

    *0 /,40"/ ".2"01 ".2"01 ".2"01+ "0-,+0" "0-,+0" "0-,+0"+ setInterval(function(){ $.ajax({url:'/data',success:function(data){ // do something }}); },500);   Con polling, el navegador envía una petición http al servidor, e inmediatamente recibe una respuesta. Está técnica supuso el primer intento para los navegadores para ofrecer información en “tiempo real”. Obviamente es una buena técnica si se sabe con exactitud cuándo va a ocurrir un evento y solicitarlo cuando el dato esté disponible, pero en general la obtención de los datos en tiempo real no es muy predecible, con lo que al final se generan muchas peticiones innecesarias, y muchas de ellas pueden que no traigan de vuelta ningún dato porque el servidor no lo tenía disponible. Long-polling, el navegador envía una petición al servidor y el servidor mantiene la conexión abierta durante un período de tiempo. Si se recibe una notificación en ese período de tiempo, se envía una respuesta al cliente con la información, y si no, el servidor cierra la conexión con el cliente. Es importante tener en cuenta que cuando existe un alto volumen de mensajes, long-polling no ofrece una mejora sustancial frente al polling.!De hecho puede ser incluso peor, puede provocar que muchas peticiones se queden en la cola pendientes de resolver.
  3. Últimamente está habiendo mucho movimiento en torno a HTML5 WebSockets,

    el cual define un canal de comunicación full-duplex entre cliente y servidor usando un único socket (antes se simulaba la bidireccionalidad usando dos canales distintos, uno para subida y otro para bajada). HTML5 WebSockets no es solamente una mejora gradual sobre las comunicaciones HTTP; representa un avance muy grande, especialmente en aplicaciones de tiempo real, u orientadas a eventos. Logo HTML5: http://www.w3.org/html/logo/
  4. ", ("10 Existe una leyenda urbana que dice que los

    WebSockets fueron desarrollados por Ian Hickson (http://en.wikipedia.org/wiki/Ian_Hickson) como medio para controlar desde un navegador web su maqueta de tren digital. De todas formas es tan sólo una leyenda, ya que Hickson desmintió que ello fuese así : “I think work on Web Sockets (TCPConnection at the time) predates my thoughts of running my train layout using Web Sockets, but Web Sockets definitely would make doing so much easier. The problem is the normal Web app controlling a single system problem: there is one computer with a serial port connection to the Märklin Interface unit, and one wants to be able to write a Web page that communicates with that computer, sending instructions and receiving updates, without having to poll, have multiple connections, use <script> streams in <iframe>s, etc.”
  5. Tipos de transmisión: Half Duplex ", ("10 Walkie talkie. El

    soldado para transportarlo no estaba incluido en el pack y conllevaba un coste adicional. Imagen: http://www.history.army.mil/books/30-17/S_7.htm
  6. var ws = new WebSocket('ws://websocketServer.com'); var ws = new WebSocket('wss://websocketServer.com');

    var ws = new WebSocket('ws://wserver.com',[proto1,proto1]); ws.onopen = function () { //Connected }; ws.onclose = function () { //Disconnected }; ws.onmessage = function (msg) { //Message received }; ws.onerror = function (err) { //error }; ws.close();  ", ("1  
  7. Fuente: http://tools.ietf.org/html/rfc6455  ", ("1/,1, ,) Handshake from the client:

    GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Handshake from the server: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat RFC 6455 define el estándar final del protocolo WebSocket. Si bien la API DOM no tiene porque sufrir cambios en su definición, el protocolo sí puede estar sometido a cambios.
  8. &*" *0 *0  *0 *0  *0 ,))&+$ "/3"/

    *0 /,40"/ ".2"01 ".2"01 ".2"01+ "0-,+0" "0-,+0" &*" *0 *0  *0 *0  *0 ", ("1 "/3"/ *0 /,40"/ "0, ("1 -$/!" ", ("1 /*" "0-,+0"+ ", ("1 /*" ", ("1 /*" ", ("1 /*" ", ("1 /*"+  ", ("1/,1, ,) Throughput entre Polling vs WebSocket.
  9. "0, ("1 AJAX vs COMET vs WEBSOCKET Petición Petición Respuesta

    vacía Navegador Servidor Respuesta Evento Evento Petición Petición Respuesta Navegador Servidor Respuesta Evento Evento Petición Respuesta Navegador Servidor Respuesta Evento Evento AJAX COMET WEBSOCKET (Con long polling)
  10. Fuente: http://caniuse.com/#feat=websockets  ", ("1/,1, ,) Mediante el uso del

    RFC, también podemos llevar los WebSockets al mundo del hardware.
  11.  ", ("1/,1, ,) HTTP REQUEST HEADER: GET /PollingStock//PollingStock HTTP/1.1

    Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://www.example.com/PollingStock/ Cookie: showInheritedConstant=false; showInheritedProtectedConstant=false; showInheritedProperty=false; showInheritedProtectedProperty=false; showInheritedMethod=false; showInheritedProtectedMethod=false; showInheritedEvent=false; showInheritedStyle=false; showInheritedEffect=false HTTP RESPONSE HEADER: HTTP/1.x 200 OK X-Powered-By: Servlet/2.5 Server: Sun Java System Application Server 9.1_02 Content-Type: text/html;charset=UTF-8 Content-Length: 21 Date: Sat, 07 Nov 2009 00:32:46 GMT Websocket en cifras. Cabecera de 871 bytes.
  12. Polling: • Caso A: 1,000 clientes haciendo polling cada segundo:

    Throughput de la red (871 x 1.000) = 871.000 bytes = 6.968.000 bps (6,6 Mbps) • Caso B: 10,000 clientes haciendo polling cada segundo: Throughput de la red (871 x 10.000) = 8.710.000 bytes = 69.680.000 bps (66 Mbps) • Caso C: 100,000 clientes haciendo polling cada 1 segundo: Throughput de la red (871 x 100.000) = 87.100.000 bytes = 696.800.000 bps (665 Mbps) WebSocket: • Use case A: 1,000 clientes reciben 1 mensaje por segundo: Throughput de la red (2 x 1.000) = 2.000 bytes = 16,000 bps (0,015 Mbps) • Use case B: 10,000 clientes reciben 1 mensaje por segundo: Throughput de la red (2 x 10.000) = 20.000 bytes = 160.000 bps (0,153 Mbps) • Use case C: 100,000 clientes reciben 1 mensaje por segundo: Throughput de la red (2 x 100.000) = 200.000 bytes = 1.600.000 bps (1,526 Mbps)  ", ("1"+ &#/0
  13. /01"+!, WebSockets en distintos lenguajes y plataformas NodeJS : Socket.IO,

    webSocket-Node, WS Java : Jetty Ruby : EventMachine Python : Pywebsocket, Tornado, Twisted Erlang : Shirasu C++ : libwebsockets .NET : SuperWebSocket Si bien NodeJS puede ser mejor al tener una arquitectura orientada a Entrada / salida y por gran rendimiento manejando conexiones concurrentes. Twisted y EventMachine también están orientados a eventos.
  14. NodeJS http://nodejs.org/ npm cheatsheet: http://blog.nodejitsu.com/npm-cheatsheet Librerías WebSocket: Socket.IO: http://socket.io/ npm

    install socket.io WS: https://github.com/einaros/ws npm install ws Documentación: Node API: http://nodejs.org/api/ How to Node: http://howtonode.org/ Mastering nodeJS (Open source): http://visionmedia.github.com/masteringnode/ Up and Running with Node.JS: http://ofps.oreilly.com/titles/9781449398583/ Hands-on nodejs: http://nodetuts.com/handson-nodejs-book.html Node Web Development: http://www.packtpub.com/node-javascript-web-development/book ,!"
  15. Node-inspector (NodeJS Debugger): https://github.com/dannycoates/node-inspector Node-supervisor : https://github.com/isaacs/node-supervisor Listado de módulos

    para nodeJS: https://github.com/joyent/node/wiki/modules Bases de datos NoSQL MongoDB http://www.mongodb.org/ Redis: http://redis.io/ Comparativa entre varias bases de datos NoSQL: http://kkovacs.eu/cassandra-vs-mongodb-vs- couchdb-vs-redis ,!"