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.



2720
2721
2722
2723
2724
2725
# File 'lib/clacky/server/http_server.rb', line 2720

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.



2718
2719
2720
# File 'lib/clacky/server/http_server.rb', line 2718

def session_id
  @session_id
end

Instance Method Details

#closed?Boolean

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

Returns:

  • (Boolean)


2728
2729
2730
# File 'lib/clacky/server/http_server.rb', line 2728

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.



2734
2735
2736
2737
2738
2739
# File 'lib/clacky/server/http_server.rb', line 2734

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.



2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
# File 'lib/clacky/server/http_server.rb', line 2743

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