class Patch::IO::Websocket::Node

Attributes

id[R]

Public Class Methods

new(id, host, port, options = {}) click to toggle source

@param [Fixnum] id @param [String] host @param [Fixnum] port @param [Hash] @option properties [Log] :log

# File lib/patch/io/websocket/node.rb, line 16
def initialize(id, host, port, options = {})
  @config = {
    :host => host,
    :port => port
  }
  @id = id
  @log = options[:log]
end

Public Instance Methods

active?() click to toggle source

Is the server active? @return [Boolean]

# File lib/patch/io/websocket/node.rb, line 74
def active?
  !@socket.nil? && @socket.active?
end
Also aliased as: running?
disable(patch) click to toggle source

Disable the message listener @return [Boolean]

# File lib/patch/io/websocket/node.rb, line 50
def disable(patch)
  @socket.disable
end
listen(patch, &callback) click to toggle source

Listen for messages with the given patch context @param [Patch] patch @param [Proc] callback callback to fire when events are received @return [Boolean]

# File lib/patch/io/websocket/node.rb, line 58
def listen(patch, &callback)
  ensure_socket.on_message do |data|
    handle_input(patch, data, &callback)
  end
  true
end
puts(patch, messages) click to toggle source

Send a message over the socket @param [Patch::Patch] patch Context @param [Array<::Patch::Message>] messages A message or messages to send @return [String, nil] If a message was sent, its JSON string; otherwise nil

# File lib/patch/io/websocket/node.rb, line 29
def puts(patch, messages)
  if running?
    unless (messages = [messages].flatten.compact).empty?
      json = messages.to_json
      @log.puts("Sending messages: #{json}") if @log
      begin
        @socket.puts(json)
      rescue Exception => exception # failsafe
        @log.exception(exception) if @log
        ::Thread.main.raise(exception)
      end
      json
    end
  else
    @log.puts("Warning: No connection") if @log
    nil
  end
end
running?()
Alias for: active?
socket() click to toggle source

Start the websocket @return [Boolean]

# File lib/patch/io/websocket/node.rb, line 67
def socket
  ensure_socket
end
Also aliased as: start
start()
Alias for: socket

Private Instance Methods

ensure_socket() click to toggle source
# File lib/patch/io/websocket/node.rb, line 81
def ensure_socket
  @socket ||= ::Patch::IO::Websocket::Socket.start(@config)
end
handle_input(patch, json_message) { |message| ... } click to toggle source

Handle a received message @param [String] json_message A raw inputted JSON message @param [Proc] callback A callback to fire with the received message @return [Message]

# File lib/patch/io/websocket/node.rb, line 89
def handle_input(patch, json_message, &callback)
  message_hash = JSON.parse(json_message, :symbolize_names => true)
  message = Message.new(message_hash)
  @log.puts("Recieved message: #{message_hash.to_json}") if @log
  yield(message) if block_given?
  message
end