Class: Clacky::Server::HttpServer::WebSocketConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/clacky/server/http_server.rb

Overview

Wraps a raw TCP socket, providing thread-safe WebSocket frame sending.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket, version) ⇒ WebSocketConnection

Returns a new instance of WebSocketConnection.



2327
2328
2329
2330
2331
2332
# File 'lib/clacky/server/http_server.rb', line 2327

def initialize(socket, version)
  @socket     = socket
  @version    = version
  @send_mutex = Mutex.new
  @closed     = false
end

Instance Attribute Details

#session_idObject

Returns the value of attribute session_id.



2325
2326
2327
# File 'lib/clacky/server/http_server.rb', line 2325

def session_id
  @session_id
end

Instance Method Details

#closed?Boolean

Returns true if the underlying socket has been detected as dead.

Returns:

  • (Boolean)


2335
2336
2337
# File 'lib/clacky/server/http_server.rb', line 2335

def closed?
  @closed
end

#send_json(data) ⇒ Object

Send a JSON-serializable object over the WebSocket. Returns true on success, false if the connection is dead.



2341
2342
2343
2344
2345
2346
# File 'lib/clacky/server/http_server.rb', line 2341

def send_json(data)
  send_raw(:text, JSON.generate(data))
rescue => e
  Clacky::Logger.debug("WS send error (connection dead): #{e.message}")
  false
end

#send_raw(type, data) ⇒ Object

Send a raw WebSocket frame. Returns true on success, false on broken/closed socket.



2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
# File 'lib/clacky/server/http_server.rb', line 2350

def send_raw(type, data)
  @send_mutex.synchronize do
    return false if @closed

    outgoing = WebSocket::Frame::Outgoing::Server.new(
      version: @version,
      data: data,
      type: type
    )
    @socket.write(outgoing.to_s)
  end
  true
rescue Errno::EPIPE, Errno::ECONNRESET, IOError, Errno::EBADF => e
  @closed = true
  Clacky::Logger.debug("WS send_raw error (client disconnected): #{e.message}")
  false
rescue => e
  @closed = true
  Clacky::Logger.debug("WS send_raw unexpected error: #{e.message}")
  false
end