-
Notifications
You must be signed in to change notification settings - Fork 10
/
chat.rb
93 lines (76 loc) · 2.01 KB
/
chat.rb
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
84
85
86
87
88
89
90
91
92
93
# Instructions: install em-websocket parser gems. Then set this script up to
# run as CGI. In a separate window, run this same script from the command
# line. Point multiple browsers at the CGI window, and change the textarea
# from in each.
require 'wunderbar/jquery'
require 'wunderbar/websocket'
PORT = 8080
if ENV['SERVER_PORT']
_html do
_style_ %{
textarea {width: 100%; height: 10em}
#error {color: red; margin-top: 1em}
#error pre {margin: 0}
}
_h1_ "Chat on port # #{PORT}"
_textarea
_div.status!
_div.error!
@socket = "ws://#{env['HTTP_HOST']}:#{PORT}/"
_script_ do
ws = WebSocket.new(@socket)
~'textarea'.on(:input) { ws.send(~this.val) }
ws.onmessage = proc do |evt|
data = JSON.parse(evt.data)
case data.type
when 'status'
~'#status'.text = data.line
when 'stderr'
~"#error".append(~'<pre>').text = data.line
else
~'textarea'.val = data.line
end
end
ws.onclose = proc do
~'textarea'.readonly = true
~'#status'.text = 'chat terminated'
end
end
end
else
# echo server
puts "Waiting on port #{PORT}"
_websocket(port: PORT) do
count = 0
timer = 10
content = ''
_.onopen do
count += 1
_ type: 'status', line: "waiting for others to join" if count == 1
_ type: 'status', line: "#{count} members in chat" if count > 1
_ type: 'msg', line: content
end
_.subscribe do |msg|
puts msg
_ type: 'msg', line: msg
content = msg
end
_.onclose do
count -= 1
_ type: 'status', line: "waiting for others to join" if count == 1
_ type: 'status', line: "#{count} members in chat" if count > 1
end
loop do
begin
sleep 60
timer -= 1
timer = 10 if count > 0
break if timer <= 0
rescue Interrupt
puts 'Shutting down'
_ type: 'status', line: 'shutting down'
break
end
end
end
end