Class: Lanet::Receiver
- Inherits:
-
Object
- Object
- Lanet::Receiver
- Defined in:
- lib/lanet/receiver.rb
Overview
Receiver class for UDP message reception
Defined Under Namespace
Classes: ReceiveError
Instance Attribute Summary collapse
-
#port ⇒ Object
readonly
Returns the value of attribute port.
Instance Method Summary collapse
- #close ⇒ Object
- #closed? ⇒ Boolean
-
#initialize(port) ⇒ Receiver
constructor
A new instance of Receiver.
- #listen(buffer_size: Config::SMALL_BUFFER, &block) ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(port) ⇒ Receiver
Returns a new instance of Receiver.
13 14 15 16 17 18 19 |
# File 'lib/lanet/receiver.rb', line 13 def initialize(port) @port = port @socket = nil @closed = false @running = false initialize_socket end |
Instance Attribute Details
#port ⇒ Object (readonly)
Returns the value of attribute port.
11 12 13 |
# File 'lib/lanet/receiver.rb', line 11 def port @port end |
Instance Method Details
#close ⇒ Object
54 55 56 57 58 59 60 |
# File 'lib/lanet/receiver.rb', line 54 def close return if @closed @running = false @socket&.close @closed = true end |
#closed? ⇒ Boolean
62 63 64 |
# File 'lib/lanet/receiver.rb', line 62 def closed? @closed end |
#listen(buffer_size: Config::SMALL_BUFFER, &block) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/lanet/receiver.rb', line 21 def listen(buffer_size: Config::SMALL_BUFFER, &block) raise ReceiveError, "Receiver is closed" if @closed raise ArgumentError, "Block is required" unless block_given? @running = true loop do break unless @running begin data, addr = @socket.recvfrom(buffer_size) ip = addr[3] block.call(data, ip) if data && ip rescue IOError, Errno::EBADF => e break if @closed raise ReceiveError, "Socket error: #{e.message}" rescue StandardError => e Config.logger.error("Error receiving message: #{e.message}") # Continue listening despite errors end end rescue Interrupt Config.logger.info("Receiver interrupted") stop ensure close unless @closed end |
#stop ⇒ Object
50 51 52 |
# File 'lib/lanet/receiver.rb', line 50 def stop @running = false end |