Sha256: 564cbace641da38d493b9b3128696138d095bb837b19589b3ef5bbdafbdf3c82

Contents?: true

Size: 1.63 KB

Versions: 1

Compression:

Stored size: 1.63 KB

Contents

# encoding: utf-8

module HTTPkit
  module Connection
    class EventMachine < EM::Connection
      def self.start_client(config, client_class)
        connection = EM.connect(config[:address], config[:port], self)
        client_class.new(config, connection)
      end

      def self.start_server(config, server_class)
        EM.start_server(config[:address], config[:port], self,
                        proc { |conn| server_class.new(config, conn) })
      end

      attr_reader :closed
      attr_writer :on_message

      def initialize(callback = proc {})
        @closed = Promise.new
        @parser = HTTP::Parser.new(self)
        callback.call(self)
      end

      def serialize(message)
        serializer = Serializer.new(message, method(:send_data))
        serializer.serialize
      end

      def receive_data(data)
        # p [__id__, :receive, data]
        # p data
        @parser << data
      rescue => ex
        # puts [ex.message, *ex.backtrace].join("\n\t")
        close(ex)
      end

      # def send_data(data)
      #   p [__id__, :send, data]
      #   # p data
      #   super
      # end

      def close(reason = nil)
        closed.reject(reason) if reason
        close_connection_after_writing
      end

      def unbind(reason = nil)
        if reason
          closed.reject(reason)
        else
          closed.fulfill
        end
      end

      def on_headers_complete(_)
        @message = Support::Message.build(@parser)
        @on_message.call(@message)
      end

      def on_body(chunk)
        @message.body.write(chunk)
      end

      def on_message_complete
        @message.close
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
httpkit-0.6.0.pre.5 lib/httpkit/connection/eventmachine.rb