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.



2443
2444
2445
2446
2447
2448
# File 'lib/clacky/server/http_server.rb', line 2443

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.



2441
2442
2443
# File 'lib/clacky/server/http_server.rb', line 2441

def session_id
  @session_id
end

Instance Method Details

#closed?Boolean

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

Returns:

  • (Boolean)


2451
2452
2453
# File 'lib/clacky/server/http_server.rb', line 2451

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.



2457
2458
2459
2460
2461
2462
# File 'lib/clacky/server/http_server.rb', line 2457

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.



2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
# File 'lib/clacky/server/http_server.rb', line 2466

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