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
-
#_join_room(conn_id, room_name) ⇒ Object
Internal: add connection ID to a room (called by WebSocketConnection#join_room).
-
#_leave_room(conn_id, room_name) ⇒ Object
Internal: remove connection ID from a room (called by WebSocketConnection#leave_room).
- #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_client_rooms(client_id) ⇒ Object
Return list of room names a given client/connection id belongs to.
- #get_clients ⇒ Object
- #get_room_connections(room_name) ⇒ Object
- #handle_upgrade(env, socket) ⇒ Object
-
#initialize ⇒ WebSocket
constructor
A new instance of WebSocket.
- #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.
38 39 40 41 42 43 44 45 46 47 |
# File 'lib/tina4/websocket.rb', line 38 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.
36 37 38 |
# File 'lib/tina4/websocket.rb', line 36 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
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/tina4/websocket.rb', line 156 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
#_join_room(conn_id, room_name) ⇒ Object
Internal: add connection ID to a room (called by WebSocketConnection#join_room). Mirrors Python’s WebSocketManager._join_room — not part of the public API.
110 111 112 113 |
# File 'lib/tina4/websocket.rb', line 110 def _join_room(conn_id, room_name) @rooms[room_name] ||= Set.new @rooms[room_name].add(conn_id) end |
#_leave_room(conn_id, room_name) ⇒ Object
Internal: remove connection ID from a room (called by WebSocketConnection#leave_room). Mirrors Python’s WebSocketManager._leave_room — not part of the public API.
117 118 119 |
# File 'lib/tina4/websocket.rb', line 117 def _leave_room(conn_id, room_name) @rooms[room_name]&.delete(conn_id) end |
#broadcast(message, exclude: nil, path: nil) ⇒ Object
88 89 90 91 92 93 94 |
# File 'lib/tina4/websocket.rb', line 88 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
138 139 140 141 142 143 |
# File 'lib/tina4/websocket.rb', line 138 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
101 102 103 104 |
# File 'lib/tina4/websocket.rb', line 101 def close(conn_id, code: 1000, reason: "") conn = @connections[conn_id] conn&.close(code: code, reason: reason) end |
#emit(event, *args) ⇒ Object
221 222 223 |
# File 'lib/tina4/websocket.rb', line 221 def emit(event, *args) @handlers[event]&.each { |h| h.call(*args) } end |
#get_client_rooms(client_id) ⇒ Object
Return list of room names a given client/connection id belongs to. Matches PHP Tina4WebSocket::getClientRooms($clientId).
127 128 129 130 131 |
# File 'lib/tina4/websocket.rb', line 127 def get_client_rooms(client_id) @rooms.each_with_object([]) do |(name, members), acc| acc << name if members.include?(client_id) end end |
#get_clients ⇒ Object
58 59 60 |
# File 'lib/tina4/websocket.rb', line 58 def get_clients @connections end |
#get_room_connections(room_name) ⇒ Object
133 134 135 136 |
# File 'lib/tina4/websocket.rb', line 133 def get_room_connections(room_name) ids = @rooms[room_name] || Set.new ids.filter_map { |id| @connections[id] } end |
#handle_upgrade(env, socket) ⇒ Object
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 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/tina4/websocket.rb', line 175 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 |
#on(event, &block) ⇒ Object
49 50 51 |
# File 'lib/tina4/websocket.rb', line 49 def on(event, &block) @handlers[event.to_sym] << block if @handlers.key?(event.to_sym) end |
#remove_from_all_rooms(conn_id) ⇒ Object
225 226 227 |
# File 'lib/tina4/websocket.rb', line 225 def remove_from_all_rooms(conn_id) @rooms.each_value { |members| members.delete(conn_id) } end |
#room_count(room_name) ⇒ Object
121 122 123 |
# File 'lib/tina4/websocket.rb', line 121 def room_count(room_name) (@rooms[room_name] || Set.new).size end |
#send_to(conn_id, message) ⇒ Object
96 97 98 99 |
# File 'lib/tina4/websocket.rb', line 96 def send_to(conn_id, ) conn = @connections[conn_id] conn&.send_text() end |
#start(host: "0.0.0.0", port: 7147) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/tina4/websocket.rb', line 62 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
80 81 82 83 84 85 86 |
# File 'lib/tina4/websocket.rb', line 80 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
53 54 55 56 |
# File 'lib/tina4/websocket.rb', line 53 def upgrade?(env) upgrade = env["HTTP_UPGRADE"] || "" upgrade.downcase == "websocket" end |