Skip to content

Instantly share code, notes, and snippets.

@k-akimoto
Last active August 29, 2015 13:57
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 k-akimoto/9665560 to your computer and use it in GitHub Desktop.
Save k-akimoto/9665560 to your computer and use it in GitHub Desktop.
2014/03/20 blog用
require 'sinatra/base'
module Websockettest2
class App < Sinatra::Base
get "/" do
erb :index
end
end
end
require 'faye/websocket'
require 'json'
module Websockettest2
class Backend
KEEPALIVE_TIME = 15
MAX_LOG_SIZE = 50
def initialize(app)
@app = app
@clients = []
@logs = Array.new
end
def call(env)
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env, nil, ping: KEEPALIVE_TIME)
ws.on :open do |event|
p [:open, ws.object_id]
@clients << ws
@clients.each do |client|
client.send({ count: @clients.size }.to_json)
end
@logs.each do |log|
p [:logs, log]
ws.send(log)
end
end
ws.on :message do |event|
p [:message, event.data]
@clients.each { |client|
client.send event.data
}
@logs.push event.data
@logs.shift if @logs.size > MAX_LOG_SIZE
end
ws.on :close do |event|
p [:close, ws.object_id, event.code]
@clients.delete(ws)
@clients.each do |client|
client.send({ count: @clients.size }.to_json)
end
ws = nil
end
ws.rack_response
else
@app.call(env)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment