Class: Patch::IO::Websocket::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/patch/io/websocket/node.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, host, port, options = {}) ⇒ Node

Returns a new instance of Node.

Parameters:

  • id (Fixnum)
  • host (String)
  • port (Fixnum)
  • (Hash)
  • properties (Hash)

    a customizable set of options



16
17
18
19
20
21
22
23
# 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

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



9
10
11
# File 'lib/patch/io/websocket/node.rb', line 9

def id
  @id
end

Instance Method Details

#active?Boolean Also known as: running?

Is the server active?

Returns:

  • (Boolean)


74
75
76
# File 'lib/patch/io/websocket/node.rb', line 74

def active?
  !@socket.nil? && @socket.active?
end

#disable(patch) ⇒ Boolean

Disable the message listener

Returns:

  • (Boolean)


50
51
52
# File 'lib/patch/io/websocket/node.rb', line 50

def disable(patch)
  @socket.disable
end

#listen(patch, &callback) ⇒ Boolean

Listen for messages with the given patch context

Parameters:

  • patch (Patch)
  • callback (Proc)

    callback to fire when events are received

Returns:

  • (Boolean)


58
59
60
61
62
63
# 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) ⇒ String?

Send a message over the socket

Parameters:

Returns:

  • (String, nil)

    If a message was sent, its JSON string; otherwise nil



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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

#socketBoolean Also known as: start

Start the websocket

Returns:

  • (Boolean)


67
68
69
# File 'lib/patch/io/websocket/node.rb', line 67

def socket
  ensure_socket
end