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 => "", :port => 8080) do |ws|
  ws.onopen    { ws.send "Hello Client!"}
  ws.onmessage { |msg| ws.send "Pong: #{msg}" }
  ws.onclose   { puts "WebSocket closed" }

The Client

[~/sinatra/sinatra-streaming/websockets-tcp-for-the-browser(development)]$ cat index.html 
    <script src=''></script>
        function debug(str){ 

        ws = new WebSocket("ws://");
        ws.onmessage = function(evt) { 
        ws.onclose = function() { 
          debug("socket closed"); 
        ws.onopen = function() {
          ws.send("hello server");
    <div id="debug"></div>
    <div id="msg"></div>
You open up a WebSocket connection simply by calling the WebSocket constructor:

var connection = new WebSocket('ws://', ['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: ' +;
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:


Hello Client!

Pong: hello server


  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

Casiano Rodriguez León 2015-01-07