Class: Tina4::WebSocket
- Inherits:
-
Object
- Object
- Tina4::WebSocket
- Defined in:
- lib/tina4/websocket.rb
Constant Summary collapse
- GUID =
WEBSOCKET_GUID
Instance Attribute Summary collapse
-
#connections ⇒ Object
readonly
Returns the value of attribute connections.
Class Method Summary collapse
-
.route(path, &block) ⇒ Object
Register a WebSocket handler for a path (class method, matching Python’s WebSocketServer.route).
Instance Method Summary collapse
- #broadcast(message, exclude: nil, path: nil) ⇒ Object
- #broadcast_to_room(room_name, message, exclude: nil) ⇒ Object
- #close(conn_id, code: 1000, reason: "") ⇒ Object
- #emit(event, *args) ⇒ Object
- #get_clients ⇒ Object
- #get_room_connections(room_name) ⇒ Object
- #handle_upgrade(env, socket) ⇒ Object
-
#initialize ⇒ WebSocket
constructor
A new instance of WebSocket.
-
#join_room_for(conn_id, room_name) ⇒ Object
── Rooms ──────────────────────────────────────────────────.
- #leave_room_for(conn_id, room_name) ⇒ Object
- #on(event, &block) ⇒ Object
- #remove_from_all_rooms(conn_id) ⇒ Object
- #room_count(room_name) ⇒ Object
- #send_to(conn_id, message) ⇒ Object
- #start(host: "0.0.0.0", port: 7147) ⇒ Object
- #stop ⇒ Object
- #upgrade?(env) ⇒ Boolean
Constructor Details
#initialize ⇒ WebSocket
Returns a new instance of WebSocket.
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/tina4/websocket.rb', line 37 def initialize @connections = {} @handlers = { open: [], message: [], close: [], error: [] } @rooms = {} # room_name => Set of conn_ids end |
Instance Attribute Details
#connections ⇒ Object (readonly)
Returns the value of attribute connections.
35 36 37 |
# File 'lib/tina4/websocket.rb', line 35 def connections @connections end |
Class Method Details
.route(path, &block) ⇒ Object
Register a WebSocket handler for a path (class method, matching Python’s WebSocketServer.route). The block receives a WebSocketConnection and should call conn.on_message / conn.on_close to wire up event callbacks.
Registers on the Router so routes work in integrated (Rack) mode.
Tina4::WebSocket.route("/chat") do |conn|
conn. { |data| conn.send(data) }
conn.on_close { puts "bye" }
end
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/tina4/websocket.rb', line 143 def self.route(path, &block) @route_handlers ||= {} @route_handlers[path] = block # Adapt to Router's (conn, event, data) style adapter = proc do |conn, event, data| case event when :open block.call(conn) when :message conn.&.call(data) when :close conn.on_close_handler&.call end end Tina4::Router.websocket(path, &adapter) end |
Instance Method Details
#broadcast(message, exclude: nil, path: nil) ⇒ Object
87 88 89 90 91 92 93 |
# File 'lib/tina4/websocket.rb', line 87 def broadcast(, exclude: nil, path: nil) @connections.each do |id, conn| next if exclude && id == exclude next if path && conn.path != path conn.send_text() end end |
#broadcast_to_room(room_name, message, exclude: nil) ⇒ Object
125 126 127 128 129 130 |
# File 'lib/tina4/websocket.rb', line 125 def broadcast_to_room(room_name, , exclude: nil) (get_room_connections(room_name)).each do |conn| next if exclude && conn.id == exclude conn.send_text() end end |
#close(conn_id, code: 1000, reason: "") ⇒ Object
100 101 102 103 |
# File 'lib/tina4/websocket.rb', line 100 def close(conn_id, code: 1000, reason: "") conn = @connections[conn_id] conn&.close(code: code, reason: reason) end |
#emit(event, *args) ⇒ Object
208 209 210 |
# File 'lib/tina4/websocket.rb', line 208 def emit(event, *args) @handlers[event]&.each { |h| h.call(*args) } end |
#get_clients ⇒ Object
57 58 59 |
# File 'lib/tina4/websocket.rb', line 57 def get_clients @connections end |
#get_room_connections(room_name) ⇒ Object
120 121 122 123 |
# File 'lib/tina4/websocket.rb', line 120 def get_room_connections(room_name) ids = @rooms[room_name] || Set.new ids.filter_map { |id| @connections[id] } end |
#handle_upgrade(env, socket) ⇒ Object
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/tina4/websocket.rb', line 162 def handle_upgrade(env, socket) key = env["HTTP_SEC_WEBSOCKET_KEY"] return unless key accept = Tina4.compute_accept_key(key) response = "HTTP/1.1 101 Switching Protocols\r\n" \ "Upgrade: websocket\r\n" \ "Connection: Upgrade\r\n" \ "Sec-WebSocket-Accept: #{accept}\r\n\r\n" socket.write(response) conn_id = SecureRandom.hex(16) ws_path = env["REQUEST_PATH"] || env["PATH_INFO"] || "/" connection = WebSocketConnection.new(conn_id, socket, ws_server: self, path: ws_path) @connections[conn_id] = connection emit(:open, connection) Thread.new do begin loop do frame = connection.read_frame break unless frame case frame[:opcode] when 0x1 # Text emit(:message, connection, frame[:data]) when 0x8 # Close break when 0x9 # Ping connection.send_pong(frame[:data]) end end rescue => e emit(:error, connection, e) ensure @connections.delete(conn_id) remove_from_all_rooms(conn_id) emit(:close, connection) socket.close rescue nil end end end |
#join_room_for(conn_id, room_name) ⇒ Object
── Rooms ──────────────────────────────────────────────────
107 108 109 110 |
# File 'lib/tina4/websocket.rb', line 107 def join_room_for(conn_id, room_name) @rooms[room_name] ||= Set.new @rooms[room_name].add(conn_id) end |
#leave_room_for(conn_id, room_name) ⇒ Object
112 113 114 |
# File 'lib/tina4/websocket.rb', line 112 def leave_room_for(conn_id, room_name) @rooms[room_name]&.delete(conn_id) end |
#on(event, &block) ⇒ Object
48 49 50 |
# File 'lib/tina4/websocket.rb', line 48 def on(event, &block) @handlers[event.to_sym] << block if @handlers.key?(event.to_sym) end |
#remove_from_all_rooms(conn_id) ⇒ Object
212 213 214 |
# File 'lib/tina4/websocket.rb', line 212 def remove_from_all_rooms(conn_id) @rooms.each_value { |members| members.delete(conn_id) } end |
#room_count(room_name) ⇒ Object
116 117 118 |
# File 'lib/tina4/websocket.rb', line 116 def room_count(room_name) (@rooms[room_name] || Set.new).size end |
#send_to(conn_id, message) ⇒ Object
95 96 97 98 |
# File 'lib/tina4/websocket.rb', line 95 def send_to(conn_id, ) conn = @connections[conn_id] conn&.send_text() end |
#start(host: "0.0.0.0", port: 7147) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/tina4/websocket.rb', line 61 def start(host: "0.0.0.0", port: 7147) require "socket" @server_socket = TCPServer.new(host, port) @running = true @server_thread = Thread.new do while @running begin client = @server_socket.accept env = {} handle_upgrade(env, client) rescue => e break unless @running end end end self end |
#stop ⇒ Object
79 80 81 82 83 84 85 |
# File 'lib/tina4/websocket.rb', line 79 def stop @running = false @server_socket&.close rescue nil @server_thread&.join(1) @connections.each_value { |conn| conn.close rescue nil } @connections.clear end |
#upgrade?(env) ⇒ Boolean
52 53 54 55 |
# File 'lib/tina4/websocket.rb', line 52 def upgrade?(env) upgrade = env["HTTP_UPGRADE"] || "" upgrade.downcase == "websocket" end |