« Back to Index

WebSockets with Vanilla JS and Ruby Faye

View original Gist on GitHub

config.ru

require "faye/websocket"
require "json"

Faye::WebSocket.load_adapter("thin")

# rackup config.ru -s thin -E production -p 9292

run -> env do
  if Faye::WebSocket.websocket?(env)
    ws = Faye::WebSocket.new(env)

    ws.send(JSON.generate :topic_timeframe => 15)

    ws.on :message do |event|
      p "Message received: #{event.data}"
      ws.send(JSON.generate :message_received => event.data)
    end

    ws.on :close do |event|
      p [:close, event.code, event.reason]
      ws = nil
    end

    ws.rack_response
  else
    [200, {"Content-Type" => "text/plain"}, ["Hello"]]
  end
end

countdown.js

function countdown(timeframe, container){
  /*
   * If timeframe is 15 (minutes)
   * Then that's 900 seconds
   * If time passed is 1:30
   * Then that's 90 seconds
   * 90%900 = 90
   * 900-90 = 810
   * 810 seconds is the time left
   * That's 13 mins 50 seconds
  */

  minute               = 60
  date                 = new Date()
  time                 = date.getMinutes() * minute + date.getSeconds()
  timeframe_in_seconds = minute * timeframe
  timeleft             = timeframe_in_seconds - time % timeframe_in_seconds
  result               = window.parseInt(timeleft / minute) + ":" + timeleft % minute

  container.innerHTML = result
}

container = document.getElementById("countdown")

function checkTimeoutValue(){
  window.setTimeout(function(){
    if (isNaN(window.topicTimeframe)) {
      checkTimeoutValue()
    } else {
      window.setInterval(countdown, 500, window.topicTimeframe, container)
    }
  }, 100)
}

checkTimeoutValue()

index.html

<html>
  <body>
    <div id="countdown"></div>

    <button id="yes">YES</button>
    <button id="no">NO</button>

    <script src="ws.js"></script>
    <script src="countdown.js"></script>
  </body>
</html>

ws.js

function log(msg){
  console.log("socket state: %s (%s)", socket.readyState, msg)
}

function connect(host){
  return new WebSocket(host)
}

function send(msg) {
  socket.send(msg)
}

socket = connect("ws://localhost:9292")

socket.onopen = function(){
  log("open")
}

socket.onclose = function(){
  log("close")
}

socket.onmessage = function(msg){
  json = JSON.parse(msg.data)

  if ("topic_timeframe" in json) {
    window.topicTimeframe = json.topic_timeframe
  }

  log(msg)
}

yes = document.getElementById("yes")
no  = document.getElementById("no")

yes.onclick = function(){
  send(this.innerHTML)
}

no.onclick = function(){
  send(this.innerHTML)
}