-
-
Save datenreisender/1196003 to your computer and use it in GitHub Desktop.
Wie mir die Lösung von AH besser gefällt
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
require 'socket' | |
class CalcMessage | |
@@operators = { | |
'ADD' => :+, | |
'MULTIPLY' => :*, | |
'SUBTRACT' => :- } | |
def initialize request | |
@command, @id, *@numbers = request.split ':' | |
end | |
def exit? | |
@command == '__SHUTDOWN__' | |
end | |
def numbers | |
@numbers.map &:to_i | |
end | |
def operator | |
@@operators[@command] | |
end | |
def answer | |
"#{@id}:#{numbers.inject &operator}" | |
end | |
end | |
class UDPConversation | |
@@max_message_size = 4097 | |
def initialize args | |
@answer_host, @answer_port = args[:answer_to].split ":" | |
listen_host, listen_port = args[:listen_on].split ":" | |
@receiver = UDPSocket.new | |
@receiver.bind listen_host, listen_port | |
end | |
def request | |
@receiver.recvfrom(@@max_message_size)[0] | |
end | |
def respond data | |
UDPSocket.new.send data, 0, @answer_host, @answer_port | |
end | |
def endless args | |
loop { respond yield request } | |
end | |
def self.endless args, &block | |
UDPConversation.new(args).endless args, &block | |
end | |
end | |
UDPConversation.endless(:listen_on => "0.0.0.0:9000", | |
:answer_to => "localhost:9001") do |request| | |
message = CalcMessage.new request | |
exit if message.exit? | |
message.answer | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment