-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathconfig.ru
56 lines (46 loc) · 1.08 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
require 'rack'
require 'rack/websocket'
require 'json'
require 'slim'
class SocketApp < Rack::WebSocket::Application
def on_open env
ChatChannel.connections << connection
msg = { username: username(env), message: 'connected' }
ChatChannel.broadcast msg.to_json
end
def on_close env
ChatChannel.connections.delete(connection)
msg = { username: username(env), message: 'disconnected' }
ChatChannel.broadcast msg.to_json
end
def on_message env, msg
ChatChannel.broadcast msg
end
def connection
@websocket_handler.instance_variable_get("@connection")
end
def username(env)
Rack::Request.new(env).params['username']
end
end
class ChatChannel
@@connections = []
def self.connections
@@connections
end
def self.broadcast msg
connections.each do |connection|
connection.send msg
end
end
end
class ChatApp
def call(env)
if env['HTTP_UPGRADE'] == "websocket"
SocketApp.new.call(env)
else
[200, {"Content-Type" => "text/html"}, [Slim::Template.new('index.slim').render]]
end
end
end
run ChatApp.new