Skip to content

Instantly share code, notes, and snippets.

@ayosec
Last active August 29, 2015 14:23
Show Gist options
  • Save ayosec/4cca7a26ea52f285fd71 to your computer and use it in GitHub Desktop.
Save ayosec/4cca7a26ea52f285fd71 to your computer and use it in GitHub Desktop.
Ruby / EventSource
source "https://rubygems.org"
GEM
remote: https://rubygems.org/
specs:
PLATFORMS
ruby
DEPENDENCIES
<!DOCTYPE html>
<meta charset="UTF-8">
<title>EventSource</title>
<h2>EventSource test</h2>
<div style="border: 1px solid black; padding: 1em;" id="output">
</div>
<script>
var output = document.getElementById("output");
var es = new EventSource("/stream");
es.onmessage = function(e) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(e.data));
output.appendChild(p);
};
es.onerror = function(e) {
es.close();
output.style.backgroundColor = "#ffcccc";
};
console.log(es);
</script>
require "socket"
server = TCPServer.new("0", 8091)
loop do
client = server.accept
Thread.new do
packet = ''
while packet.include?("\r\n\r\n") == false
packet << client.recv(1024)
end
if packet[/\A(\S+)\s+(\S+)\s/, 1]
method = $1
path = $2
puts "[#{Time.now}] #{method} #{path}"
case path
when "/"
page = File.read("index.html")
lines = [
"HTTP/1.1 200 OK",
"Content-Type: text/html",
"Content-Length: #{page.length}",
"Connection: close"
].join("\r\n")
client.write(lines + "\r\n\r\n")
client.write(page)
when "/stream"
client.write("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n")
10.times do |i|
sleep 0.5
client.write(%[data: { "number": #{i} }\r\n\r\n])
client.flush
end
else
lines = [
"HTTP/1.1 404 Not Found",
"Content-Type: text/html",
"Connection: close"
].join("\r\n")
client.write(lines + "\r\n\r\n<h1>Not Found</h1>")
end
else
client.write "NO HTTP"
end
client.shutdown
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment