Sha256: 8d360a5e7b3a632aed5490df97bb4adfc6f53fc6689bf0f2145ee5fa01e1c607

Contents?: true

Size: 1.48 KB

Versions: 4

Compression:

Stored size: 1.48 KB

Contents

##
# States of a connection
class Midori::Connection
  include Midori::Server

  # @!attribute data
  #   @return [String] string buffer of data to send
  attr_accessor :data

  # Init Connection with socket
  # @param [IO] socket raw socket
  def initialize(socket)
    @registered = false
    @socket = socket
    @monitor = nil
    @close_flag = false
    @buffer = ''
    listen(socket)
  end

  # Register events of connection
  # @param [IO] socket raw socket
  def listen(socket)
    EventLoop.register(socket, :rw) do |monitor|
      @monitor = monitor
      if monitor.readable?
        receive_data(monitor)
      end
      if monitor.writable?
        if !@buffer.empty?
          send_buffer
        elsif @close_flag
          close_connection
        end
      end
    end
  end

  # Send message to client
  # @param [Midori::Response | String] data data to send
  def send_data(data)
    @buffer << (data.is_a?(String) ? data : data.to_s)
    send_buffer
    nil
  end

  # Send buffer immediately
  private def send_buffer
    if @monitor.writable?
      written = @socket.write_nonblock(@buffer)
      @buffer = @buffer.byteslice(written..-1)
    end
    nil
  rescue IO::EAGAINWaitWritable => _e
    # :nocov:
    # Unknown Reason Resource Conflict
    nil
    # :nocov:
  end

  # Close the connection
  def close_connection
    EventLoop.deregister @socket
    @socket.close
  end

  # Close the connection after writing
  def close_connection_after_writing
    @close_flag = true
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
midori.rb-0.5.4 lib/midori/connection.rb
midori.rb-0.5.3.1 lib/midori/connection.rb
midori.rb-0.5.3 lib/midori/connection.rb
midori.rb-0.5.2 lib/midori/connection.rb