ruby 我的第一个简单的IPC解决方案,通过unix socket

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 我的第一个简单的IPC解决方案,通过unix socket相关的知识,希望对你有一定的参考价值。

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"

以上是关于ruby 我的第一个简单的IPC解决方案,通过unix socket的主要内容,如果未能解决你的问题,请参考以下文章

ruby Ruby:IPC任务计划程序

ruby Ruby:Llenar un hash con valores por defecto

在 Ruby 中读取文件的第一行

ruby Ejemplo de como subir un attachment a Basecamp desde Ruby

Winsock 结构来存储 IPC 的路径

在循环中创建子进程时如何与父进程进行IPC(Ruby)