Rick Carlino

Personal blog of Rick Carlino, senior software engineer at Qualia Labs, co-founder of Fox.Build Makerspace. Former co-founder of FarmBot.

Ruby Websocket Services with Websocketd

Websocketd is a program similar to xinetd which allows users to host any command line application over a websocket by simply reading and writing to STDIN/STDOUT.

Let’s say we wanted to stream the AAPL stock quote to a live dashboard

Example code:

#!/Users/me/.rvm/rubies/ruby-2.1.2/bin/ruby

require 'stock_quote'

STDOUT.puts "Welcome! Streaming AAPL stock price now..."
STDOUT.flush

while true
  STDOUT.puts StockQuote::Stock.quote("aapl").ask
  STDOUT.flush
  sleep 2
end

After running the command below…

chmod +x ./script.rb

…the Ruby snippet could be served to a browser by running the following:

websocketd --port=8080 ./script.rb

That’s all there is to it. You can now connect using a Websocket from any modern browser.

Try running this from your JS console to see all incoming messages from the server:

// Connect
var ws = new WebSocket("ws://localhost:8080");

// Print all incoming messages to console
ws.onmessage = function (e) {
  console.log(e);
};

If you enjoyed this article, please consider sharing it on sites like Hacker News or Lobsters.