Created
April 14, 2016 21:08
-
-
Save mustmodify/ddd8b1f04de252655555d21dd90d4ae0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UDPRecipient < Valuable | |
has_value :ip, :allow_blank => false | |
has_value :port, :default => 11235 | |
has_value :logger, :default => Logger.new('./udp.log') | |
has_value :max_message_size, :default => 2**10 | |
def udp_socket | |
@udp ||= UDPSocket.new.tap do |udp| | |
raise "Please supply an ip to UDPRecipient, like UDPRecipient.new(ip: '1.2.3.4')" unless ip | |
udp.bind(ip, port) | |
logger.warn "Listening at udp://#{ip}:#{port}" | |
end | |
end | |
def listen | |
begin | |
message = udp.recvfrom(max_message_size) | |
logger.debug message | |
yield message if block_given? | |
end while 1 | |
end | |
def fire | |
listen | |
ensure | |
logger.warn('closing connection') | |
logger.try(:close) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment