Sha256: 5b4f475d2e99127f52f5a2e22a878e77dbf4b72bb62153e1be089d382dcf5772

Contents?: true

Size: 935 Bytes

Versions: 3

Compression:

Stored size: 935 Bytes

Contents

# frozen_string_literal: true
module LiteCable
  module Server
    # Sends pings to sockets
    class HeartBeat
      BEAT_INTERVAL = 3

      def initialize
        @sockets = []
        run
      end

      def add(socket)
        @sockets << socket
      end

      def remove(socket)
        @sockets.delete(socket)
      end

      def stop
        @stopped = true
      end

      def run
        Thread.new do
          Thread.current.abort_on_exception = true
          loop do
            break if @stopped

            unless @sockets.empty?
              msg = ping_message Time.now.to_i
              @sockets.each do |socket|
                socket.transmit msg
              end
            end

            sleep BEAT_INTERVAL
          end
        end
      end

      private

      def ping_message(time)
        { type: LiteCable::INTERNAL[:message_types][:ping], message: time }.to_json
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
litecable-0.4.2 lib/lite_cable/server/heart_beat.rb
litecable-0.4.1 lib/lite_cable/server/heart_beat.rb
litecable-0.4.0 lib/lite_cable/server/heart_beat.rb