Created
December 12, 2013 21:34
-
-
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'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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