class Discordrb::WebSocket

Utility wrapper class that abstracts an instance of WSCS. Useful should we decide that WSCS isn’t good either - in that case we can just switch to something else

Attributes

close_handler[R]
error_handler[R]
message_handler[R]
open_handler[R]

Public Class Methods

new(endpoint, open_handler, message_handler, close_handler, error_handler) click to toggle source

Create a new WebSocket and connect to the given endpoint. @param endpoint [String] Where to connect to. @param open_handler [#call] The handler that should be called when the websocket has opened successfully. @param message_handler [#call] The handler that should be called when the websocket receives a message. The

handler can take one parameter which will have a `data` attribute for normal messages and `code` and `data` for
close frames.

@param close_handler [#call] The handler that should be called when the websocket is closed due to an internal

error. The error will be passed as the first parameter to the handler.

@param error_handler [#call] The handler that should be called when an error occurs in another handler. The error

will be passed as the first parameter to the handler.
# File lib/discordrb/websocket.rb, line 31
def initialize(endpoint, open_handler, message_handler, close_handler, error_handler)
  Discordrb::LOGGER.debug "Using WSCS version: #{::WebSocket::Client::Simple::VERSION}"

  @open_handler = open_handler
  @message_handler = message_handler
  @close_handler = close_handler
  @error_handler = error_handler

  instance = self # to work around WSCS's weird way of handling blocks

  @client = ::WebSocket::Client::Simple.connect(endpoint) do |ws|
    ws.on(:open) { instance.open_handler.call }
    ws.on(:message) do |msg|
      # If the message has a code attribute, it is in reality a close message
      if msg.code
        instance.close_handler.call(msg)
      else
        instance.message_handler.call(msg.data)
      end
    end
    ws.on(:close) { |err| instance.close_handler.call(err) }
    ws.on(:error) { |err| instance.error_handler.call(err) }
  end
end

Public Instance Methods

close() click to toggle source

Close the WebSocket connection

# File lib/discordrb/websocket.rb, line 63
def close
  @client.close
end
send(data) click to toggle source

Send data over this WebSocket @param data [String] What to send

# File lib/discordrb/websocket.rb, line 58
def send(data)
  @client.send(data)
end
thread() click to toggle source

@return [Thread] the internal WSCS thread

# File lib/discordrb/websocket.rb, line 68
def thread
  @client.thread
end