Rick Carlino

Lead software developer and co-founding member @ Farmbot, Inc.

Co-founder @ Fox.Build Makerspace, St. Charles, IL.

Reddit Twitter GitHub LinkedIn Stack Overflow Email Updates

Ruby Websocket Services with Websocketd

November 13 2014

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:

1
2
3
4
5
6
7
8
9
10
11
12
#!/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…

1
chmod +x ./script.rb

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

1
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:

1
2
3
4
5
6
// Connect
var ws = new WebSocket("ws://localhost:8080");
// Print all incoming messages to console
ws.onmessage = function(e) { console.log(e); };
(C) 2017 Rick Carlino