Ruby y WebSockets: TCP for the Browser

Esta sección está sacada del blog de Ilya Grigorik .

WebSockets in HTML5 were designed from the ground up to be data agnostic (binary or text) with support for full-duplex communication.

WebSockets are TCP for the web-browser. They require only a single connection, which translates into much better resource utilization for both the server and the client.

Likewise, WebSockets are proxy and firewall aware, can operate over SSL and leverage the HTTP channel to accomplish all of the above - your existing load balancers, proxies and routers will work just fine.

The Server

[~/sinatra/sinatra-streaming/websockets-tcp-for-the-browser(development)]$ cat server.rb
require 'em-websocket'

EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
  ws.onopen    { ws.send "Hello Client!"}
  ws.onmessage { |msg| ws.send "Pong: #{msg}" }
  ws.onclose   { puts "WebSocket closed" }
end

The Client

[~/sinatra/sinatra-streaming/websockets-tcp-for-the-browser(development)]$ cat index.html 
<html>
  <head>
    <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script>
    <script>
      $(document).ready(function(){
        function debug(str){ 
          $("#debug").append("<p>"+str+"</p>"); 
        };

        ws = new WebSocket("ws://www.example.com:8080/websocket");
        ws.onmessage = function(evt) { 
          $("#msg").append("<p>"+evt.data+"</p>"); 
        };
        ws.onclose = function() { 
          debug("socket closed"); 
        };
        ws.onopen = function() {
          debug("connected...");
          ws.send("hello server");
        };
      });
    </script>
  </head>
  <body>
    <div id="debug"></div>
    <div id="msg"></div>
  </body>
</html>
You open up a WebSocket connection simply by calling the WebSocket constructor:

var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);
Notice the ws:. This is the new URL schema for WebSocket connections. There is also wss: for secure WebSocket connection the same way https: is used for secure HTTP connections.

Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.

The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing protocol property of WebSocket object.

// When the connection is open, send some data to the server
connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
connection.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

// Log messages from the server
connection.onmessage = function (e) {
  console.log('Server: ' + e.data);
};
As soon as we have a connection to the server (when the open event is fired) we can start sending data to the server using the send('your message') method on the connection object. It used to support only strings, but in the latest spec it now can send binary messages too. To send binary data, you can use either Blob or ArrayBuffer bject.

The server might send us messages at any time. Whenever this happens the onmessage callback fires. The callback receives an event object and the actual message is accessible via the data property. parrafoEjecución

[~/sinatra/sinatra-streaming/websockets-tcp-for-the-browser(development)]$ ruby server.rb

Cuando abrimos index.html con el navegador obtenemos una página como esta:

connected...

Hello Client!

Pong: hello server

Véase

  1. Ruby and WebSockets: TCP for the Browser
  2. Introducing WebSockets: Bringing Sockets to the Web by Malte Ubl and Eiji Kitamura 2010
  3. Clean, simple websockets on Sinatra example by Austen Conrad Austen Conrad YouTube



Subsecciones
Casiano Rodriguez León 2015-06-18