Sha256: b97995d5fc6a9fadb80b69bc4d57b0d2246c8986b59f34d288818c76ab7edb12

Contents?: true

Size: 812 Bytes

Versions: 3

Compression:

Stored size: 812 Bytes

Contents

require 'json'

module Propono
  class TcpListenerError < ProponoError
  end

  class TcpListener

    def self.listen(&processor)
      new(&processor).listen
    end

    def initialize(&processor)
      raise TcpListenerError.new("Please provide a block to call for each message") unless block_given?
      @processor = processor
    end

    def listen
      loop { receive_and_process }
    end

    private

    def receive_and_process
      client = server.accept
      tcp_data = client.recvfrom(1024)[0]
      client.close
      Thread.new { process_tcp_data(tcp_data) }
    end

    def process_tcp_data(tcp_data)
      json = JSON.parse(tcp_data)
      @processor.call(json['topic'], json['message'])
    end

    def server
      @server ||= TCPServer.open(Propono.config.tcp_port)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
propono-0.8.2 lib/propono/services/tcp_listener.rb
propono-0.8.0 lib/propono/services/tcp_listener.rb
propono-0.7.0 lib/propono/services/tcp_listener.rb