Sha256: b7ac8d33d2b97521ad08b66265b7ef9fe2a339521a3af5ad88334ef7ef44a440

Contents?: true

Size: 1.97 KB

Versions: 5

Compression:

Stored size: 1.97 KB

Contents

require 'sinatra'
require 'sinatra-websocket'
require_relative '../lib/pressure'

set :server, 'thin'
set :sockets, []

data = {}

def random_string
  (0...8).map { (65 + rand(26)).chr }.join
end

Thread.new do
  loop do
    data = [random_string, random_string, random_string, random_string]
    sleep(1.0 / 0.2)
  end
end

pressure = Pressure.new(no_wrap: false) do
  data
end

pressure.wrapper_template = {
  someKey: 'Some Value',
  anotherKey: 'Another Value'
}

get '/' do
  if !request.websocket?
    erb :index
  else
    request.websocket do |ws|
      ws.onopen do
        pressure << ws
        puts "Connected: #{pressure.sockets.length}"
      end
      ws.onmessage do |msg|
        EM.next_tick { pressure.sockets.each { |socket| socket.send(msg) } }
      end
      ws.onclose do
        warn('websocket closed')
        pressure.delete ws
      end
    end
  end
end

__END__
@@ index
<html>
  <body>
     <h1>Pressure Demo</h1>
     <form id="form">
       <input type="text" id="input" value="send a message"></input>
     </form>
     <div id="msgs"></div>
  </body>

  <script type="text/javascript">
    window.onload = function(){
      (function(){
        var show = function(el){
          return function(msg){ el.innerHTML = msg + '<br />' + el.innerHTML; }
        }(document.getElementById('msgs'));

        var ws       = new WebSocket('ws://' + window.location.host + window.location.pathname);
        ws.onopen    = function()  { show('websocket opened'); };
        ws.onclose   = function()  { show('websocket closed'); }
        ws.onmessage = function(m) { show('websocket message: ' +  m.data); };

        var sender = function(f){
          var input     = document.getElementById('input');
          input.onclick = function(){ input.value = "" };
          f.onsubmit    = function(){
            ws.send(input.value);
            input.value = "";
            return false;
          }
        }(document.getElementById('form'));
      })();
    }
  </script>
</html>

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
pressure-0.1.6 examples/demo.rb
pressure-0.1.5 examples/demo.rb
pressure-0.1.4 examples/demo.rb
pressure-0.1.3 examples/demo.rb
pressure-0.1.1 examples/demo.rb