25. サーバー
• EventStream用のパスを用意
$connections = []
get '/stream', :provides => 'text/event-stream' do
stream :keep_open do |out|
$connections << out
out.callback { $connections.delete out }
out.errback do
logger.warn "lost connection"
$connections.delete out
end
end
end
26. サーバー
• イベント送信
post '/admin/save' do
c = Challenge.find_by(id: params['id'])
c ||= Challenge.new
admin_block do
c.id = params['id']
…(中略)
c.save
if c.status == 'show'
json = { "type" => "challenge", "id" => c.id, "abstract" => c.abstract, "point" => c.point }
$connections.each { |out| out << "data: #{JSON.generate(json)}nn" }
end
redirect '/admin/main'
end
end
27. クライアント
• クライアントからServer-sent eventsで接続
var es = new EventSource('/stream');
es.onmessage = function(e) {
var data = JSON.parse(e.data);
if (data.type === "challenge") {
notification.newNotify({title: "新しい問題があります",
detail: "新しい問題が追加されました!n 問題:“ + data.abstract
});
return;
}
}