Created
October 16, 2014 15:08
-
-
Save jeremytregunna/b5fa7cb858c3b4d48085 to your computer and use it in GitHub Desktop.
This file contains 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
# 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