# class Listen::TCP::Broadcaster

### Public Class Methods

new(host, port) click to toggle source

Initializes a Celluloid::IO-powered TCP-broadcaster

@param [String] host to broadcast on @param [String] port to broadcast on

Note: Listens on all addresses when host is nil

    # File lib/listen/tcp/broadcaster.rb, line 17
    def initialize(host, port)
      @sockets = []
      _log :debug, format('Broadcaster: tcp server listening on: %s:%s',
                          host, port)
      @server = TCPServer.new(host, port)
    rescue
      _log :error, format('Broadcaster.initialize: %s:%s', $ERROR_INFO,
                          $ERROR_POSITION * "\n")
      raise
    end

### Public Instance Methods

_log(type, message) click to toggle source

    # File lib/listen/tcp/broadcaster.rb, line 66
    def _log(type, message)
      Celluloid::Logger.send(type, message)
    end

_unicast(socket, payload) click to toggle source

    # File lib/listen/tcp/broadcaster.rb, line 70
    def _unicast(socket, payload)
      socket.write(payload)
      true
    rescue IOError, Errno::ECONNRESET, Errno::EPIPE
      _log :debug, "Broadcaster failed: #{socket.inspect}"
      false
    end

broadcast(payload) click to toggle source

Broadcasts given payload to all connected sockets

    # File lib/listen/tcp/broadcaster.rb, line 44
    def broadcast(payload)
      active_sockets = @sockets.select do |socket|
        _unicast(socket, payload)
      end
      @sockets.replace(active_sockets)
    end

finalize() click to toggle source

Cleans up sockets and server

    # File lib/listen/tcp/broadcaster.rb, line 34
    def finalize
      @sockets.map(&:close) if @sockets
      @sockets = nil

      return unless @server
      @server.close
      @server = nil
    end

run() click to toggle source

Continuously accept and handle incoming connections

    # File lib/listen/tcp/broadcaster.rb, line 52
      def run
        while (socket = @server.accept)
          @sockets << socket
        end
      rescue Celluloid::Task::TerminatedError
        _log :debug, "TCP adapter was terminated: #{$ERROR_INFO}"
      rescue
        _log :error, format('Broadcaster.run: %s:%s', $ERROR_INFO,
                            $ERROR_POSITION * "\n")
        raise
      end

      private

      def _log(type, message)
        Celluloid::Logger.send(type, message)
      end

      def _unicast(socket, payload)
        socket.write(payload)
        true
      rescue IOError, Errno::ECONNRESET, Errno::EPIPE
        _log :debug, "Broadcaster failed: #{socket.inspect}"
        false
      end
    end

start() click to toggle source

Asynchronously start accepting connections

    # File lib/listen/tcp/broadcaster.rb, line 29
    def start
      async.run
    end