Skip to content

Instantly share code, notes, and snippets.

@jeremytregunna
Created September 15, 2014 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremytregunna/893032d3ebb29c35ca75 to your computer and use it in GitHub Desktop.
Save jeremytregunna/893032d3ebb29c35ca75 to your computer and use it in GitHub Desktop.
# Heavy State Sync
require 'faye/websocket'
require 'json'
class HeavyStateSync
KEEPALIVE_INTERVAL = 15
def initialize(app)
@app = app
@clients = []
@last_state = {}
end
def call(env)
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env, ['chat', 'whiteboard'], { ping: KEEPALIVE_INTERVAL })
ws.on :open do |event|
@clients << ws
ws.send @last_state.to_json
end
ws.on :message do |event|
@last_state = JSON.parse(event.data)
ws.send @last_state.to_json
end
ws.on :close do |event|
@clients.delete(ws)
ws = nil
end
ws.rack_response
else
if @app
@app.call(env)
else
[200, {"Content-Type" => "application/json"}, [{error: "Unknown error"}.to_json]]
end
end
end
end
EM.error_handler do |e|
p "*** ERROR ***"
puts e
puts e.backtrace
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment