Skip to content

Instantly share code, notes, and snippets.

@kangguru
Created December 12, 2013 21:34
Show Gist options
  • Save kangguru/7935887 to your computer and use it in GitHub Desktop.
Save kangguru/7935887 to your computer and use it in GitHub Desktop.
Turn any application that uses STDOUT into a WebSocket server. Inspired by https://github.com/joewalnes/websocketd but written in ruby. $ ./websocket.rb start 'iostat -w 1 disk0'
#!/usr/bin/env ruby
require 'em-websocket'
require 'thor'
module Handler
def initialize(args)
@ws = args
end
def receive_data(data)
@buf ||= ''
@buf << data
while line = @buf.slice!(/(.+)\r?\n/) do
@ws.send(line)
end
end
end
class WebSocket < Thor
desc "start COMMAND", "starts the websocket server"
option :host, default: "0.0.0.0"
option :port, default: 8080
option :debug, default: false, type: :boolean
def start(command)
EventMachine::WebSocket.start(host: options[:host], port: options[:port], debug: options[:debug]) do |ws|
ws.onopen { EM.popen(command, Handler, ws) }
ws.onclose { puts "WebSocket closed" }
ws.onerror { |e| puts "Error: #{e.message}" }
end
end
end
WebSocket.start(ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment