Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: b13098f99f
Fetching contributors…

Cannot retrieve contributors at this time

file 70 lines (60 sloc) 1.682 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
require 'socket'
#require 'puggernaut/client/tcp'

module Puggernaut
  class Client
    
    attr_accessor :connections
    
    def initialize(servers={})
      @connections = {}
      @retry = []
      @servers = servers
    end
    
    def connect(host, port)
      host_port = "#{host}:#{port}"
      @connections[host_port] ||= TCPSocket.open(host, port)
    end
    
    def close
      @connections.each do |host_port, connection|
        connection.close
        logger.info "Client#close - #{http_port}"
      end
    end
    
    def logger
      Puggernaut.logger
    end
    
    def say(messages)
      messages.each do |room, message|
        message =
          if message.is_a?(::Array)
            message.collect { |m| "#{room}|#{m}" }.join("\n")
          else
            "#{room}|#{message}"
          end
        @servers.each do |host, port|
          send host, port, message
        end
      end
    end
    
    private
    
    def send(host, port, data, try_retry=true)
      try if try_retry
      begin
        logger.info "Client#send - #{host}:#{port} - #{data}"
        connection = connect(host, port)
        connection.print(data)
        response = connection.gets
        raise 'not ok' if !response || !response.include?('OK')
      rescue Exception => e
        logger.info "Client#send - Exception - #{e.message} - #{host}:#{port} - #{data}"
        @retry << [ host, port, data ]
        @retry.shift if @retry.length > 10
      end
    end
    
    def try
      @retry.length.times do
        host, port, data = @retry.shift
        @connections.delete("#{host}:#{port}")
        send host, port, data, false
      end
    end
  end
end
Something went wrong with that request. Please try again.