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_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.
-
#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.
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
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/tina4/websocket.rb', line 152 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
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
134 135 136 137 138 139 |
# File 'lib/tina4/websocket.rb', line 134 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
217 218 219 |
# File 'lib/tina4/websocket.rb', line 217 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).
123 124 125 126 127 |
# File 'lib/tina4/websocket.rb', line 123 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
129 130 131 132 |
# File 'lib/tina4/websocket.rb', line 129 def get_room_connections(room_name) ids = @rooms[room_name] || Set.new ids.filter_map { |id| @connections[id] } end |
#handle_upgrade(env, socket) ⇒ Object
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 207 208 209 210 211 212 213 214 215 |
# File 'lib/tina4/websocket.rb', line 171 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 ──────────────────────────────────────────────────
108 109 110 111 |
# File 'lib/tina4/websocket.rb', line 108 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
113 114 115 |
# File 'lib/tina4/websocket.rb', line 113 def leave_room_for(conn_id, room_name) @rooms[room_name]&.delete(conn_id) 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
221 222 223 |
# File 'lib/tina4/websocket.rb', line 221 def remove_from_all_rooms(conn_id) @rooms.each_value { |members| members.delete(conn_id) } end |
#room_count(room_name) ⇒ Object
117 118 119 |
# File 'lib/tina4/websocket.rb', line 117 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 |