Method: EventMachine.watch

Defined in:
lib/eventmachine.rb

.watch(io, handler = nil, *args, &blk) ⇒ Object

watch registers a given file descriptor or IO object with the eventloop. The file descriptor will not be modified (it will remain blocking or non-blocking).

The eventloop can be used to process readable and writable events on the file descriptor, using EventMachine::Connection#notify_readable= and EventMachine::Connection#notify_writable=

EventMachine::Connection#notify_readable? and EventMachine::Connection#notify_writable? can be used to check what events are enabled on the connection.

To detach the file descriptor, use EventMachine::Connection#detach

Examples:


module SimpleHttpClient
  def notify_readable
    header = @io.readline

    if header == "\r\n"
      # detach returns the file descriptor number (fd == @io.fileno)
      fd = detach
    end
  rescue EOFError
    detach
  end

  def unbind
    EM.next_tick do
      # socket is detached from the eventloop, but still open
      data = @io.read
    end
  end
end

EventMachine.run {
  sock = TCPSocket.new('site.com', 80)
  sock.write("GET / HTTP/1.0\r\n\r\n")
  conn = EventMachine.watch(sock, SimpleHttpClient)
  conn.notify_readable = true
}

Author:

  • Riham Aldakkak (eSpace Technologies)



732
733
734
# File 'lib/eventmachine.rb', line 732

def EventMachine::watch io, handler=nil, *args, &blk
  attach_io io, true, handler, *args, &blk
end