Sha256: a1d1bd97f933a2f082d9623028e1e086baf81ef1ca5b563a594d88855eccd755

Contents?: true

Size: 1.55 KB

Versions: 1

Compression:

Stored size: 1.55 KB

Contents

require 'ffi-rzmq'
require 'msgpack'

require_relative 'socket/sender'
require_relative 'socket/server'

module SubZero
  class Socket
    include Loggable
    include Sender
    include Server

    class Error        < StandardError; end
    class TimeoutError < Socket::Error; end

    attr_reader :config

    def initialize config = Configuration.default
      @config = config
    end

    def context
      context = ZMQ::Context.create(1)
      fail Socket::Error, 'failed to create context' unless context
      yield context
      check! context.terminate
    rescue Socket::Error
      check! context.terminate
      raise
    end

    def socket context
      socket = context.socket ZMQ::DEALER
      socket.identity = SecureRandom.hex(10)
      check! socket.connect("tcp://#{config[:ip]}:#{config[:port]}")
      yield socket
      check! socket.close
    rescue Socket::Error
      check! socket.close
      raise
    end

    def send_message socket, message
      frames = message.to_source
      last   = frames.pop
      frames.each { |f| check! socket.send_string f.to_s, ZMQ::SNDMORE }
      check! socket.send_string last
    end

    def receive_message socket, request
      check! socket.recv_strings(frames = [])
      Message.parse frames, request
    end

    def check! result_code
      return if ZMQ::Util.resultcode_ok? result_code

      fail Socket::Error, "operation failed, errno [#{ZMQ::Util.errno}], " +
        "description [#{ZMQ::Util.error_string}]"
    rescue
      raise Socket::Error "operation failed, cannot have errno"
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sub_zero-0.0.5 lib/sub_zero/socket.rb