Created
September 15, 2014 21:14
-
-
Save jeremytregunna/893032d3ebb29c35ca75 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