require 'socket'
require 'base64'
require 'active_support/core_ext/object/blank'
class Vault
def hello(value = nil)
ret = 'data from the vault'
ret += ": |#{value}|"
ret
end
end
class UServer
def initialize(sock, front_object)
raise "Socket at #{sock} already exists" if File.exists? sock
server = UNIXServer.new sock
loop {
# Waiting for connection
socket = server.accept
# Got Request
packet = Marshal.load(Base64.strict_decode64(socket.readline.rstrip))
# send message to front end object
if packet[1].blank?
reply = front_object.send(packet[0])
else
reply = front_object.send(packet[0], *packet[1]) # note the splat operator
end
# Sending Response
socket.write Base64.strict_encode64(Marshal.dump(reply)) + "\n"
socket.close
}
end
end
pid = fork {
server = UServer.new '/tmp/simple.sock', Vault.new
}
Process.waitpid pid
require 'socket'
require 'base64'
class UClient
def initialize(sock)
@sock = sock
end
def method_missing(symbol, *args)
socket = UNIXSocket.new(@sock)
# Sending
socket.write Base64.strict_encode64(Marshal.dump([symbol, args])) + "\n"
# Getting Response
ret = Marshal.load(Base64.strict_decode64(socket.readline.rstrip))
socket.close
ret
end
end
client = UClient.new '/tmp/simple.sock'
puts client.hello
puts client.hello "New\nWorld"