This repository has been archived by the owner on Apr 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.ru
83 lines (70 loc) · 1.75 KB
/
config.ru
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
require 'bundler/setup'
require 'sinatra'
class IndexApp
def call(env)
[200, {"Content-type" => "text/html"}, [(<<-PAGE)]]
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ASYNC</title>
<script type="text/javascript">
var source = new EventSource('/messages');
source.onmessage = function(e) {
showMessage(e.data);
};
source.onopen = function(e) {
// Connection was opened.
};
source.onerror = function(e) {
console.log("Source Error", e)
if (e.eventPhase == EventSource.CLOSED) {
// Connection was closed.
}
};
var showMessage = function(msg) {
var out = document.getElementById('stream');
var d = document.createElement('div')
var b = document.createElement('strong')
var now = new Date;
b.innerHTML = msg;
d.innerHTML = now.getHours() + ":" + now.getMinutes() + ":" +now.getSeconds() + " ";
d.appendChild(b);
out.appendChild(d);
};
</script>
</head>
<body>
<div id="stream">
</div>
</body>
</html>
PAGE
end
end
$connections = []
class StreamApp < Sinatra::Base
def connections
$connections
end
get "/" do
content_type "text/event-stream"
stream(:keep_open) { |out|
connections << out
}
end
post "/" do
data = "data: #{params[:message]}\n\n"
connections.each { |out| out << data }
"sent '#{params[:message]}'\n"
end
end
app = Rack::Builder.new do
map "/messages" do
run StreamApp.new
end
map "/" do
run IndexApp.new
end
end
run app