Class: Buschtelefon::NetTattler

Inherits:
Tattler
  • Object
show all
Defined in:
lib/buschtelefon/net_tattler.rb

Instance Attribute Summary collapse

Attributes inherited from Tattler

#connections

Instance Method Summary collapse

Methods inherited from Tattler

#connect, #feed, #knowledge, #load_messages, #transfer_knowledge

Constructor Details

#initialize(host: "127.0.0.1", port: 0) ⇒ NetTattler

Returns a new instance of NetTattler.



8
9
10
11
12
13
14
# File 'lib/buschtelefon/net_tattler.rb', line 8

def initialize(host: "127.0.0.1", port: 0)
  super()
  @socket = UDPSocket.new
  @socket.bind(host, port)
  @host = @socket.local_address.ip_address
  @port = @socket.local_address.ip_port
end

Instance Attribute Details

#hostObject

Returns the value of attribute host.



6
7
8
# File 'lib/buschtelefon/net_tattler.rb', line 6

def host
  @host
end

#portObject

Returns the value of attribute port.



6
7
8
# File 'lib/buschtelefon/net_tattler.rb', line 6

def port
  @port
end

#socketObject

Returns the value of attribute socket.



6
7
8
# File 'lib/buschtelefon/net_tattler.rb', line 6

def socket
  @socket
end

Instance Method Details

#connect_remote(host:, port:) ⇒ Object



36
37
38
39
40
# File 'lib/buschtelefon/net_tattler.rb', line 36

def connect_remote(host:, port:)
  find_or_build_remote_tattler(host: host, port: port).tap do |remote_tattler|
    connect(remote_tattler)
  end
end

#inquire_remote_neighborsObject



42
43
44
# File 'lib/buschtelefon/net_tattler.rb', line 42

def inquire_remote_neighbors
  remote_connections.each { |remote_tattler| remote_tattler.inquire }
end

#listen(&_callback) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/buschtelefon/net_tattler.rb', line 16

def listen(&_callback)
  puts "Started UDP server on #{@host}:#{@port}..."

  Socket.udp_server_loop_on([@socket]) do |message, message_source|
    remote_tattler = find_or_build_remote_tattler(
      host: message_source.remote_address.ip_address,
      port: message_source.remote_address.ip_port
    )

    if message == "\x05"
      # puts "#{@port} got inquiry from #{remote_tattler}. Is connected to #{@connections.inspect}"
      handle_knowledge_inquiry(remote_tattler)
    else
      gossip = Gossip.new(message)
      handle_incoming_gossip(gossip)
      yield(gossip, remote_tattler) if block_given?
    end
  end
end

#remote_connectionsObject



46
47
48
# File 'lib/buschtelefon/net_tattler.rb', line 46

def remote_connections
  @connections.select { |tattler| tattler.is_a?(RemoteTattler) }
end

#to_sObject



50
51
52
# File 'lib/buschtelefon/net_tattler.rb', line 50

def to_s
  "#{@host}:#{@port}"
end