Last Updated: February 25, 2016
·
1.281K
· blazeeboy

Sharing your Screen on the network with Ruby

what if you're in an event and want to share your screen with the audience ? there is no data show/projector?, well you'll have to search for a screen sharing application, or make your own :)
the following will work for OSX only as the screencapture command works only on mac machines.

require 'socket'
require 'base64'

Refresh = 1 # seconds to refresh image on server
screen_capture_command = 'screencapture -C -x tmp.png'
image = ''
latest = Time.now
server = TCPServer.new 3000

loop do
  Thread.start(server.accept) do |client|
    if Time.now-latest>=Refresh
        system(screen_capture_command)
        latest = Time.now
        File.open('tmp.png', 'rb') do |file| 
            image = 'data:image/png;base64,'+Base64.encode64(file.read) 
        end
    end
    client.puts '<html><head>'+
                "<script>setTimeout(function(){document.location.reload();},#{Refresh*1000});</script>"+
                '</head><body style="padding:0px;margin:0px;">'+
                "<img src=\"#{image}\" style=\"height:100%;\"/>"+
                '</body></html>'
    client.close
  end
end

the above is simple straight forward, get an image periodically and embed it in an auto refreshing HTML page and give it the user.

that works like charm for both mobile and desktops.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip