-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.ru
77 lines (63 loc) · 1.44 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
require 'json'
require 'slim'
require 'faye/websocket'
require 'thread'
require 'sinatra/base'
module Timer
class WebServer < Sinatra::Base
enable :inline_templates
get '/' do
slim :index
end
end
class Main
def initialize(app=nil)
@clients = []
@web = app
Thread.new do
while true do
@clients.each { |ws| ws.send(JSON.generate({ time: Time.now.strftime('%d.%m.%Y %T') })) }
sleep 1
end
end
end
def call(env)
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env, nil, { ping: 15 })
ws.on(:open) { puts 'open'; @clients << ws }
ws.on(:close) { puts 'close'; @clients.delete(ws); ws = nil }
ws.on(:message) { |event| p JSON.parse(event.data) }
ws.rack_response
else
@web.call(env)
# [101, {'Content-Type' => 'text/html'}, ['Hello']]
end
end
end
end
use Timer::Main
run Timer::WebServer.new
__END__
@@ index
html
h1 Timer
div#root
@@ layout
doctype html
html
head
body
== yield
@@ index
div#root
javascript:
let ws = new WebSocket('ws://localhost:5000/');
let timerListener = (response) => {
document.getElementById('root').innerHTML = `<h1> ${JSON.parse(response.data).time} </h1>`;
};
timer = setInterval(function() {
if (document.readyState == 'complete') {
ws.onmessage = timerListener;
clearInterval(timer);
}
}, 10);