-
-
Save kenichi/de652d1ef7705716c126 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'reel' | |
require 'json' | |
require 'pry' | |
class Server < Reel::Server::HTTP | |
include Celluloid::Logger | |
def initialize host = '127.0.0.1', port = 4567 | |
info "listening on #{host}:#{port}" | |
super host, port, &method(:on_connection) | |
end | |
def on_connection connection | |
connection.each_request do |request| | |
case request.url | |
when '/' | |
connection.respond :ok, <<-HTML | |
<!doctype html> | |
<html> | |
<head> | |
<title>sse</title> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> | |
</head> | |
<body> | |
sse! | |
<script> | |
var es = new EventSource('/sse'); | |
es.onopen = function(e){ console.log('es opened!'); }; | |
es.onmessage = function(e){ console.log('message: ' + e.data); }; | |
es.addEventListener('current-time', function(e) { | |
console.log('current-time: ' + e.data); | |
}); | |
es.onclose = function(e){ console.log('es closed!'); }; | |
</script> | |
</body> | |
</html> | |
HTML | |
when '/sse' | |
connection.detach | |
headers = { 'Content-Type' => 'text/event-stream' } | |
connection.respond :ok, headers | |
async.message connection.socket | |
begin | |
now = Time.now.to_f | |
sleep now.ceil - now + 0.001 | |
loop do | |
data = { time: Time.now }.to_json | |
output = "event: current-time\ndata: #{data}\n\n" | |
debug "sending '#{output}'" | |
connection.socket.write output | |
sleep 1 | |
end | |
rescue IOError, Errno::EPIPE, Errno::ECONNRESET => e | |
error e.message | |
ensure | |
connection.close | |
end | |
end | |
end | |
end | |
def message socket | |
5.times { | |
socket.write "data: THIS IS A MESSAGE!\n\n" | |
sleep 5 | |
} | |
end | |
end | |
Server.new | |
sleep |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment