Module: EventMachine
- Defined in:
- lib/em/future.rb,
lib/em/queue.rb,
lib/em/timers.rb,
lib/em/channel.rb,
lib/em/version.rb,
lib/em/callback.rb,
lib/em/iterator.rb,
lib/em/streamer.rb,
lib/em/processes.rb,
lib/em/protocols.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/pure_ruby.rb,
lib/em/spawnable.rb,
lib/em/tick_loop.rb,
lib/eventmachine.rb,
lib/em/connection.rb,
lib/em/deferrable.rb,
lib/em/file_watch.rb,
lib/evma/callback.rb,
lib/jeventmachine.rb,
lib/em/process_watch.rb,
lib/em/protocols/stomp.rb,
lib/em/protocols/socks4.rb,
lib/em/protocols/tcptest.rb,
lib/em/protocols/memcache.rb,
lib/em/protocols/saslauth.rb,
lib/em/protocols/linetext2.rb,
lib/em/protocols/postgres3.rb,
lib/em/protocols/httpclient.rb,
lib/em/protocols/smtpclient.rb,
lib/em/protocols/smtpserver.rb,
lib/em/protocols/httpclient2.rb,
lib/em/protocols/line_and_text.rb,
lib/em/protocols/object_protocol.rb,
lib/em/protocols/header_and_content.rb,
ext/rubymain.cpp,
ext/fastfilereader/rubymain.cpp
Overview
–
- Author
-
Francis Cianfrocca (gmail: blackhedd)
- Homepage
- Date
-
15 Nov 2006
See EventMachine and EventMachine::Connection for documentation and usage examples.
Copyright © 2006-07 by Francis Cianfrocca. All Rights Reserved. Gmail: blackhedd
This program is free software; you can redistribute it and/or modify it under the terms of either: 1) the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version; or 2) Ruby’s License.
See the file COPYING for complete licensing information.
Defined Under Namespace
Modules: Deferrable, Protocols, UuidGenerator Classes: Channel, Connection, ConnectionError, ConnectionNotBound, DatagramObject, DefaultDeferrable, DeferrableChildProcess, Error, EvmaKeyboard, EvmaTCPClient, EvmaTCPServer, EvmaUDPSocket, EvmaUNIXClient, EvmaUNIXServer, FastFileReader, FileNotFoundException, FileStreamer, FileWatch, Iterator, JEM, LoopbreakReader, PeriodicTimer, ProcessWatch, Queue, Reactor, Selectable, SpawnedProcess, StreamObject, SystemCmd, TickLoop, Timer, UnknownTimerFired, Unsupported, YieldBlockFromSpawnedProcess
Constant Summary collapse
- VERSION =
"0.12.11"
- TimerFired =
TODO: These event numbers are defined in way too many places. DRY them up.
INT2NUM(100)
- ConnectionData =
INT2NUM(101)
- ConnectionUnbound =
INT2NUM(102)
- ConnectionAccepted =
INT2NUM(103)
- ConnectionCompleted =
INT2NUM(104)
- LoopbreakSignalled =
INT2NUM(105)
- P =
EventMachine::Protocols
- ConnectionNotifyReadable =
INT2NUM(106)
- ConnectionNotifyWritable =
INT2NUM(107)
- SslHandshakeCompleted =
INT2NUM(108)
Class Attribute Summary collapse
-
.reactor_thread ⇒ Object
readonly
Exposed to allow joining on the thread, when run in a multithreaded environment.
-
.threadpool ⇒ Object
readonly
:nodoc:.
-
.threadpool_size ⇒ Object
Size of the EventMachine.defer threadpool (defaults to 20).
Class Method Summary collapse
-
.add_oneshot_timer(interval) ⇒ Object
#add_oneshot_timer – Changed 04Oct06: intervals from the caller are now in milliseconds, but our native-ruby processor still wants them in seconds.
-
.add_periodic_timer(*args, &block) ⇒ Object
EventMachine#add_periodic_timer adds a periodic timer to the event loop.
-
.add_timer(*args, &block) ⇒ Object
EventMachine#add_timer adds a one-shot timer to the event loop.
-
.attach(io, handler = nil, *args, &blk) ⇒ Object
Attaches an IO object or file descriptor to the eventloop as a regular connection.
- .attach_fd(fileno, watch_mode) ⇒ Object
-
.attach_io(io, watch_mode, handler = nil, *args) ⇒ Object
:nodoc:.
-
.bind_connect(bind_addr, bind_port, server, port = nil, handler = nil, *args) ⇒ Object
EventMachine::bind_connect is like EventMachine::connect, but allows for a local address/port to bind the connection to.
- .bind_connect_server(bind_addr, bind_port, server, port) ⇒ Object
-
.Callback(object = nil, method = nil, &blk) ⇒ Object
Utility method for coercing arguments to an object that responds to #call Accepts an object and a method name to send to, or a block, or an object that responds to call.
-
.cancel_timer(timer_or_sig) ⇒ Object
Cancel a timer using its signature.
-
.close_connection(sig, after_writing) ⇒ Object
#close_connection The extension version does NOT raise any kind of an error if an attempt is made to close a non-existent connection.
-
.connect(server, port = nil, handler = nil, *args, &blk) ⇒ Object
EventMachine#connect initiates a TCP connection to a remote server and sets up event-handling for the connection.
-
.connect_server(server, port) ⇒ Object
#connect_server.
-
.connect_unix_domain(socketname, *args, &blk) ⇒ Object
Make a connection to a Unix-domain socket.
-
.connect_unix_server(chain) ⇒ Object
#connect_unix_server.
-
.connection_count ⇒ Object
Returns the total number of connections (file descriptors) currently held by the reactor.
-
.defer(op = nil, callback = nil, &blk) ⇒ Object
#defer is for integrating blocking operations into EventMachine’s control flow.
- .detach_fd(sig) ⇒ Object
-
.disable_proxy(from) ⇒ Object
disable_proxy takes just one argument, a Connection that has proxying enabled via enable_proxy.
-
.enable_proxy(from, to, bufsize = 0, length = 0) ⇒ Object
enable_proxy allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor.
-
.epoll ⇒ Object
#epoll is a harmless no-op in the pure-Ruby implementation.
-
.epoll=(val) ⇒ Object
Epoll is a no-op for Java.
- .epoll? ⇒ Boolean
-
.error_handler(cb = nil, &blk) ⇒ Object
Catch-all for errors raised during event loop callbacks.
-
.event_callback(target, opcode, data) ⇒ Object
:nodoc:.
-
.fork_reactor(&block) ⇒ Object
fork_reactor forks a new process and calls EM#run inside of it, passing your block.
- .get_connection_count ⇒ Object
- .get_max_timer_count ⇒ Object
-
.get_max_timers ⇒ Object
Gets the current maximum number of allowed timers.
-
.get_outbound_data_size(sig) ⇒ Object
#get_outbound_data_size.
-
.get_peername(sig) ⇒ Object
#get_peername.
-
.heartbeat_interval ⇒ Object
Retrieve the heartbeat interval.
-
.heartbeat_interval=(time) ⇒ Object
Set the heartbeat interval.
-
.initialize_event_machine ⇒ Object
class Connection < com.rubyeventmachine.Connection def associate_callback_target sig # No-op for the time being.
- .invoke_popen(cmd) ⇒ Object
- .is_notify_readable(sig) ⇒ Object
- .is_notify_writable(sig) ⇒ Object
- .kqueue ⇒ Object
- .kqueue=(val) ⇒ Object
- .kqueue? ⇒ Boolean
-
.library_type ⇒ Object
This is mostly useful for automated tests.
-
.next_tick(pr = nil, &block) ⇒ Object
Schedules a proc for execution immediately after the next “turn” through the reactor core.
-
.open_datagram_socket(address, port, handler = nil, *args) ⇒ Object
EventMachine#open_datagram_socket is for support of UDP-based protocols.
-
.open_keyboard(handler = nil, *args) ⇒ Object
(Experimental).
-
.open_udp_socket(server, port) ⇒ Object
Currently a no-op for Java.
-
.popen(cmd, handler = nil, *args) {|c| ... } ⇒ Object
Run an external process.
-
.reactor_running? ⇒ Boolean
Tells you whether the EventMachine reactor loop is currently running.
-
.reactor_thread? ⇒ Boolean
Returns true if the calling thread is the same thread as the reactor.
-
.read_keyboard ⇒ Object
#read_keyboard.
-
.reconnect(server, port, handler) ⇒ Object
Connect to a given host/port and re-use the provided EventMachine::Connection instance – Observe, the test for already-connected FAILS if we call a reconnect inside post_init, because we haven’t set up the connection in @conns by that point.
-
.release_machine ⇒ Object
release_machine.
-
.run(blk = nil, tail = nil, &block) ⇒ Object
EventMachine::run initializes and runs an event loop.
-
.run_block(&block) ⇒ Object
Sugars a common use case.
-
.run_deferred_callbacks ⇒ Object
– The is the responder for the loopback-signalled event.
-
.run_machine ⇒ Object
run_machine.
-
.schedule(*a, &b) ⇒ Object
Runs the given callback on the reactor thread, or immediately if called from the reactor thread.
-
.send_data(sig, data, length) ⇒ Object
#send_data.
-
.send_datagram(sig, data, length, address, port) ⇒ Object
#send_datagram.
-
.send_file_data(sig, filename) ⇒ Object
#send_file_data.
-
.set_comm_inactivity_timeout(sig, interval) ⇒ Object
#set_comm_inactivity_timeout.
-
.set_descriptor_table_size(n_descriptors = nil) ⇒ Object
Sets the maximum number of file or socket descriptors that your process may open.
-
.set_effective_user(username) ⇒ Object
A wrapper over the setuid system call.
-
.set_max_timer_count(num) ⇒ Object
#set_max_timer_count is a harmless no-op in pure Ruby, which doesn’t have a built-in limit on the number of available timers.
-
.set_max_timers(ct) ⇒ Object
Sets the maximum number of timers and periodic timers that may be outstanding at any given time.
- .set_notify_readable(sig, mode) ⇒ Object
- .set_notify_writable(sig, mode) ⇒ Object
-
.set_quantum(mills) ⇒ Object
For advanced users.
-
.set_rlimit_nofile(n_descriptors) ⇒ Object
#set_rlimit_nofile is a no-op in the pure-Ruby implementation.
-
.set_timer_quantum(q) ⇒ Object
#set_timer_quantum in milliseconds.
-
.signal_loopbreak ⇒ Object
#signal_loopbreak.
-
.spawn(&block) ⇒ Object
Spawn an erlang-style process.
-
.spawn_threadpool ⇒ Object
:nodoc:.
-
.ssl? ⇒ Boolean
#ssl? is not implemented for pure-Ruby implementation.
-
.start_server(server, port = nil, handler = nil, *args, &block) ⇒ Object
EventMachine::start_server initiates a TCP server (socket acceptor) on the specified IP address and port.
-
.start_tcp_server(server, port) ⇒ Object
#start_tcp_server.
- .start_tls(sig) ⇒ Object
-
.start_unix_domain_server(filename, *args, &block) ⇒ Object
Start a Unix-domain server.
-
.start_unix_server(filename) ⇒ Object
#start_unix_server.
-
.stop ⇒ Object
#stop.
-
.stop_event_loop ⇒ Object
stop_event_loop may called from within a callback method while EventMachine’s processing loop is running.
-
.stop_server(signature) ⇒ Object
Stop a TCP server socket that was started with EventMachine#start_server.
-
.stop_tcp_server(sig) ⇒ Object
#stop_tcp_server.
-
.system(cmd, *args, &cb) ⇒ Object
EM::system is a simple wrapper for EM::popen.
-
.tick_loop(*a, &b) ⇒ Object
Creates and immediately starts an EventMachine::TickLoop.
-
.watch(io, handler = nil, *args, &blk) ⇒ Object
EventMachine::watch registers a given file descriptor or IO object with the eventloop.
-
.watch_file(filename, handler = nil, *args) ⇒ Object
EventMachine’s file monitoring API.
-
.watch_process(pid, handler = nil, *args) ⇒ Object
EventMachine’s process monitoring API.
-
.yield(&block) ⇒ Object
:nodoc:.
-
.yield_and_notify(&block) ⇒ Object
:nodoc:.
Class Attribute Details
.reactor_thread ⇒ Object (readonly)
Exposed to allow joining on the thread, when run in a multithreaded environment. Performing other actions on the thread has undefined semantics.
127 128 129 |
# File 'lib/eventmachine.rb', line 127 def reactor_thread @reactor_thread end |
.threadpool ⇒ Object (readonly)
:nodoc:
1009 1010 1011 |
# File 'lib/eventmachine.rb', line 1009 def threadpool @threadpool end |
.threadpool_size ⇒ Object
Size of the EventMachine.defer threadpool (defaults to 20)
1012 1013 1014 |
# File 'lib/eventmachine.rb', line 1012 def threadpool_size @threadpool_size end |
Class Method Details
.add_oneshot_timer(interval) ⇒ Object
#add_oneshot_timer – Changed 04Oct06: intervals from the caller are now in milliseconds, but our native-ruby processor still wants them in seconds.
55 56 57 |
# File 'lib/em/pure_ruby.rb', line 55 def add_oneshot_timer interval Reactor.instance.install_oneshot_timer(interval / 1000) end |
.add_periodic_timer(*args, &block) ⇒ Object
EventMachine#add_periodic_timer adds a periodic timer to the event loop. It takes the same parameters as the one-shot timer method, EventMachine#add_timer. This method schedules execution of the given block repeatedly, at intervals of time at least as great as the number of seconds given in the first parameter to the call.
Usage example
The following sample program will write a dollar-sign to stderr every five seconds. (Of course if the program defined network clients and/or servers, they would be doing their work while the periodic timer is counting off.)
EventMachine::run {
EventMachine::add_periodic_timer( 5 ) { $stderr.write "$" }
}
Also see EventMachine::PeriodicTimer
339 340 341 342 343 344 |
# File 'lib/eventmachine.rb', line 339 def self.add_periodic_timer *args, &block interval = args.shift code = args.shift || block EventMachine::PeriodicTimer.new(interval, code) end |
.add_timer(*args, &block) ⇒ Object
EventMachine#add_timer adds a one-shot timer to the event loop. Call it with one or two parameters. The first parameters is a delay-time expressed in seconds (not milliseconds). The second parameter, if present, must be a proc object. If a proc object is not given, then you can also simply pass a block to the method call.
EventMachine#add_timer may be called from the block passed to EventMachine#run or from any callback method. It schedules execution of the proc or block passed to add_timer, after the passage of an interval of time equal to at least the number of seconds specified in the first parameter to the call.
EventMachine#add_timer is a non-blocking call. Callbacks can and will be called during the interval of time that the timer is in effect. There is no built-in limit to the number of timers that can be outstanding at any given time.
Usage example
This example shows how easy timers are to use. Observe that two timers are initiated simultaneously. Also, notice that the event loop will continue to run even after the second timer event is processed, since there was no call to EventMachine#stop_event_loop. There will be no activity, of course, since no network clients or servers are defined. Stop the program with Ctrl-C.
EventMachine::run {
puts "Starting the run now: #{Time.now}"
EventMachine::add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
EventMachine::add_timer( 10 ) { puts "Executing timer event: #{Time.now}" }
}
Also see EventMachine::Timer – Changed 04Oct06: We now pass the interval as an integer number of milliseconds.
309 310 311 312 313 314 315 316 317 318 |
# File 'lib/eventmachine.rb', line 309 def self.add_timer *args, &block interval = args.shift code = args.shift || block if code # check too many timers! s = add_oneshot_timer((interval.to_f * 1000).to_i) @timers[s] = code s end end |
.attach(io, handler = nil, *args, &blk) ⇒ Object
Attaches an IO object or file descriptor to the eventloop as a regular connection. The file descriptor will be set as non-blocking, and EventMachine will process receive_data and send_data events on it as it would for any other connection.
To watch a fd instead, use EventMachine::watch, which will not alter the state of the socket and fire notify_readable and notify_writable events instead.
717 718 719 |
# File 'lib/eventmachine.rb', line 717 def EventMachine::attach io, handler=nil, *args, &blk attach_io io, false, handler, *args, &blk end |
.attach_fd(fileno, watch_mode) ⇒ Object
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
# File 'lib/jeventmachine.rb', line 192 def self.attach_fd fileno, watch_mode # 3Aug09: We could pass in the actual SocketChannel, but then it would be modified (set as non-blocking), and # we would need some logic to make sure detach_fd below didn't clobber it. For now, we just always make a new # SocketChannel for the underlying file descriptor # if fileno.java_kind_of? SocketChannel # ch = fileno # ch.configureBlocking(false) # fileno = nil # elsif fileno.java_kind_of? java.nio.channels.Channel if fileno.java_kind_of? java.nio.channels.Channel field = fileno.getClass.getDeclaredField('fdVal') field.setAccessible(true) fileno = field.get(fileno) else raise ArgumentError, 'attach_fd requires Java Channel or POSIX fileno' unless fileno.is_a? Fixnum end if fileno == 0 raise "can't open STDIN as selectable in Java =(" elsif fileno.is_a? Fixnum # 8Aug09: The following code is specific to the sun jvm's SocketChannelImpl. Is there a cross-platform # way of implementing this? If so, also remember to update EventableSocketChannel#close and #cleanup fd = FileDescriptor.new fd.set_field 'fd', fileno ch = SocketChannel.open ch.configureBlocking(false) ch.kill ch.set_field 'fd', fd ch.set_field 'fdVal', fileno ch.set_field 'state', ch.get_field('ST_CONNECTED') end @em.attachChannel(ch,watch_mode) end |
.attach_io(io, watch_mode, handler = nil, *args) ⇒ Object
:nodoc:
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 |
# File 'lib/eventmachine.rb', line 721 def EventMachine::attach_io io, watch_mode, handler=nil, *args # :nodoc: klass = klass_from_handler(Connection, handler, *args) if !watch_mode and klass.public_instance_methods.any?{|m| [:notify_readable, :notify_writable].include? m.to_sym } raise ArgumentError, "notify_readable/writable with EM.attach is not supported. Use EM.watch(io){ |c| c.notify_readable = true }" end if io.respond_to?(:fileno) fd = defined?(JRuby) ? JRuby.runtime.getDescriptorByFileno(io.fileno).getChannel : io.fileno else fd = io end s = attach_fd fd, watch_mode c = klass.new s, *args c.instance_variable_set(:@io, io) c.instance_variable_set(:@fd, fd) @conns[s] = c block_given? and yield c c end |
.bind_connect(bind_addr, bind_port, server, port = nil, handler = nil, *args) ⇒ Object
EventMachine::bind_connect is like EventMachine::connect, but allows for a local address/port to bind the connection to.
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 |
# File 'lib/eventmachine.rb', line 636 def self.bind_connect bind_addr, bind_port, server, port=nil, handler=nil, *args begin port = Integer(port) rescue ArgumentError, TypeError # there was no port, so server must be a unix domain socket # the port argument is actually the handler, and the handler is one of the args args.unshift handler if handler handler = port port = nil end if port klass = klass_from_handler(Connection, handler, *args) s = if port if bind_addr bind_connect_server bind_addr, bind_port.to_i, server, port else connect_server server, port end else connect_unix_server server end c = klass.new s, *args @conns[s] = c block_given? and yield c c end |
.bind_connect_server(bind_addr, bind_port, server, port) ⇒ Object
79 80 81 |
# File 'lib/em/pure_ruby.rb', line 79 def bind_connect_server bind_addr, bind_port, host, port EvmaTCPClient.connect(bind_addr, bind_port, host, port).uuid end |
.Callback(object = nil, method = nil, &blk) ⇒ Object
Utility method for coercing arguments to an object that responds to #call Accepts an object and a method name to send to, or a block, or an object that responds to call.
cb = EM.Callback{ |msg| puts(msg) }
cb.call('hello world')
cb = EM.Callback(Object, :puts)
cb.call('hello world')
cb = EM.Callback(proc{ |msg| puts(msg) })
cb.call('hello world')
15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/em/callback.rb', line 15 def self.Callback(object = nil, method = nil, &blk) if object && method lambda { |*args| object.send method, *args } else if object.respond_to? :call object else blk || raise(ArgumentError) end end end |
.cancel_timer(timer_or_sig) ⇒ Object
Cancel a timer using its signature. You can also use EventMachine::Timer#cancel
348 349 350 351 352 353 354 |
# File 'lib/eventmachine.rb', line 348 def self.cancel_timer timer_or_sig if timer_or_sig.respond_to? :cancel timer_or_sig.cancel else @timers[timer_or_sig] = false if @timers.has_key?(timer_or_sig) end end |
.close_connection(sig, after_writing) ⇒ Object
#close_connection The extension version does NOT raise any kind of an error if an attempt is made to close a non-existent connection. Not sure whether we should. For now, we’ll raise an error here in that case.
93 94 95 96 |
# File 'lib/em/pure_ruby.rb', line 93 def close_connection target, after_writing selectable = Reactor.instance.get_selectable( target ) or raise "unknown close_connection target" selectable.schedule_close after_writing end |
.connect(server, port = nil, handler = nil, *args, &blk) ⇒ Object
EventMachine#connect initiates a TCP connection to a remote server and sets up event-handling for the connection. You can call EventMachine#connect in the block supplied to EventMachine#run or in any callback method.
EventMachine#connect takes the IP address (or hostname) and port of the remote server you want to connect to. It also takes an optional handler Module which you must define, that contains the callbacks that will be invoked by the event loop on behalf of the connection.
See the description of EventMachine#start_server for a discussion of the handler Module. All of the details given in that description apply for connections created with EventMachine#connect.
Usage Example
Here’s a program which connects to a web server, sends a naive request, parses the HTTP header of the response, and then (antisocially) ends the event loop, which automatically drops the connection (and incidentally calls the connection’s unbind method).
module DumbHttpClient
def post_init
send_data "GET / HTTP/1.1\r\nHost: _\r\n\r\n"
@data = ""
@parsed = false
end
def receive_data data
@data << data
if !@parsed and @data =~ /[\n][\r]*[\n]/m
@parsed = true
puts "RECEIVED HTTP HEADER:"
$`.each {|line| puts ">>> #{line}" }
puts "Now we'll terminate the loop, which will also close the connection"
EventMachine::stop_event_loop
end
end
def unbind
puts "A connection has terminated"
end
end
EventMachine::run {
EventMachine::connect "www.bayshorenetworks.com", 80, DumbHttpClient
}
puts "The event loop has ended"
There are times when it’s more convenient to define a protocol handler as a Class rather than a Module. Here’s how to do this:
class MyProtocolHandler < EventMachine::Connection
def initialize *args
super
# whatever else you want to do here
end
#.......your other class code
end
If you do this, then an instance of your class will be instantiated to handle every network connection created by your code or accepted by servers that you create. If you redefine #post_init in your protocol-handler class, your #post_init method will be called inside the call to #super that you will make in your #initialize method (if you provide one).
– EventMachine::connect initiates a TCP connection to a remote server and sets up event-handling for the connection. It internally creates an object that should not be handled by the caller. HOWEVER, it’s often convenient to get the object to set up interfacing to other objects in the system. We return the newly-created anonymous-class object to the caller. It’s expected that a considerable amount of code will depend on this behavior, so don’t change it.
Ok, added support for a user-defined block, 13Apr06. This leads us to an interesting choice because of the presence of the post_init call, which happens in the initialize method of the new object. We call the user’s block and pass the new object to it. This is a great way to do protocol-specific initiation. It happens AFTER post_init has been called on the object, which I certainly hope is the right choice. Don’t change this lightly, because accepted connections are different from connected ones and we don’t want to have them behave differently with respect to post_init if at all possible.
630 631 632 |
# File 'lib/eventmachine.rb', line 630 def self.connect server, port=nil, handler=nil, *args, &blk bind_connect nil, nil, server, port, handler, *args, &blk end |
.connect_server(server, port) ⇒ Object
#connect_server. Return a connection descriptor to the caller. TODO, what do we return here if we can’t connect?
75 76 77 |
# File 'lib/em/pure_ruby.rb', line 75 def connect_server host, port bind_connect_server nil, nil, host, port end |
.connect_unix_domain(socketname, *args, &blk) ⇒ Object
Make a connection to a Unix-domain socket. This is not implemented on Windows platforms. The parameter socketname is a String which identifies the Unix-domain socket you want to connect to. socketname is the name of a file on your local system, and in most cases is a fully-qualified path name. Make sure that your process has enough local permissions to open the Unix-domain socket. See also the documentation for #connect. This method behaves like #connect in all respects except for the fact that it connects to a local Unix-domain socket rather than a TCP socket.
Note that this method is simply an alias for #connect, which can connect to both TCP and Unix-domain sockets – For making connections to Unix-domain sockets. Eventually this has to get properly documented and unified with the TCP-connect methods. Note how nearly identical this is to EventMachine#connect
784 785 786 |
# File 'lib/eventmachine.rb', line 784 def self.connect_unix_domain socketname, *args, &blk connect socketname, *args, &blk end |
.connect_unix_server(chain) ⇒ Object
#connect_unix_server
117 118 119 |
# File 'lib/em/pure_ruby.rb', line 117 def connect_unix_server chain EvmaUNIXClient.connect(chain).uuid end |
.connection_count ⇒ Object
Returns the total number of connections (file descriptors) currently held by the reactor. Note that a tick must pass after the ‘initiation’ of a connection for this number to increment. It’s usually accurate, but don’t rely on the exact precision of this number unless you really know EM internals.
For example, $count will be 0 in this case:
EM.run {
EM.connect("rubyeventmachine.com", 80)
$count = EM.connection_count
}
In this example, $count will be 1 since the connection has been established in the next loop of the reactor.
EM.run {
EM.connect("rubyeventmachine.com", 80)
EM.next_tick {
$count = EM.connection_count
}
}
913 914 915 |
# File 'lib/eventmachine.rb', line 913 def self.connection_count self.get_connection_count end |
.defer(op = nil, callback = nil, &blk) ⇒ Object
#defer is for integrating blocking operations into EventMachine’s control flow. Call #defer with one or two blocks, as shown below (the second block is optional):
operation = proc {
# perform a long-running operation here, such as a database query.
"result" # as usual, the last expression evaluated in the block will be the return value.
}
callback = proc {|result|
# do something with result here, such as send it back to a network client.
}
EventMachine.defer( operation, callback )
The action of #defer is to take the block specified in the first parameter (the “operation”) and schedule it for asynchronous execution on an internal thread pool maintained by EventMachine. When the operation completes, it will pass the result computed by the block (if any) back to the EventMachine reactor. Then, EventMachine calls the block specified in the second parameter to #defer (the “callback”), as part of its normal, synchronous event handling loop. The result computed by the operation block is passed as a parameter to the callback. You may omit the callback parameter if you don’t need to execute any code after the operation completes.
Caveats
Note carefully that the code in your deferred operation will be executed on a separate thread from the main EventMachine processing and all other Ruby threads that may exist in your program. Also, multiple deferred operations may be running at once! Therefore, you are responsible for ensuring that your operation code is threadsafe. [Need more explanation and examples.] Don’t write a deferred operation that will block forever. If so, the current implementation will not detect the problem, and the thread will never be returned to the pool. EventMachine limits the number of threads in its pool, so if you do this enough times, your subsequent deferred operations won’t get a chance to run. [We might put in a timer to detect this problem.]
– OBSERVE that #next_tick hacks into this mechanism, so don’t make any changes here without syncing there.
Running with $VERBOSE set to true gives a warning unless all ivars are defined when they appear in rvalues. But we DON’T ever want to initialize @threadqueue unless we need it, because the Ruby threads are so heavyweight. We end up with this bizarre way of initializing @threadqueue because EventMachine is a Module, not a Class, and has no constructor.
981 982 983 984 985 986 987 988 989 990 991 |
# File 'lib/eventmachine.rb', line 981 def self.defer op = nil, callback = nil, &blk unless @threadpool require 'thread' @threadpool = [] @threadqueue = ::Queue.new @resultqueue = ::Queue.new spawn_threadpool end @threadqueue << [op||blk,callback] end |
.detach_fd(sig) ⇒ Object
228 229 230 231 232 |
# File 'lib/jeventmachine.rb', line 228 def self.detach_fd sig if ch = @em.detachChannel(sig) ch.get_field 'fdVal' end end |
.disable_proxy(from) ⇒ Object
disable_proxy takes just one argument, a Connection that has proxying enabled via enable_proxy. Calling this method will remove that functionality and your connection will begin receiving data via receive_data again.
1318 1319 1320 |
# File 'lib/eventmachine.rb', line 1318 def self.disable_proxy(from) EM::stop_proxy(from.signature) end |
.enable_proxy(from, to, bufsize = 0, length = 0) ⇒ Object
enable_proxy allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor. This is especially useful for proxies where high performance is required. Propogating data from a server response all the way up to Ruby, and then back down to the reactor to be sent back to the client, is often unnecessary and incurs a significant performance decrease.
The two arguments are Connections, ‘from’ and ‘to’. ‘from’ is the connection whose inbound data you want relayed back out. ‘to’ is the connection to write it to.
Once you call this method, the ‘from’ connection will no longer get receive_data callbacks from the reactor, except in the case that ‘to’ connection has already closed when attempting to write to it. You can see in the example, that proxy_target_unbound will be called when this occurs. After that, further incoming data will be passed into receive_data as normal.
Note also that this feature supports different types of descriptors - TCP, UDP, and pipes. You can relay data from one kind to another.
Example:
module ProxyConnection
def initialize(client, request)
@client, @request = client, request
end
def post_init
EM::enable_proxy(self, @client)
end
def connection_completed
send_data @request
end
def proxy_target_unbound
close_connection
end
def unbind
@client.close_connection_after_writing
end
end
module ProxyServer
def receive_data(data)
(@buf ||= "") << data
if @buf =~ /\r\n\r\n/ # all http headers received
EM.connect("10.0.0.15", 80, ProxyConnection, self, data)
end
end
end
EM.run {
EM.start_server("127.0.0.1", 8080, ProxyServer)
}
1311 1312 1313 |
# File 'lib/eventmachine.rb', line 1311 def self.enable_proxy(from, to, bufsize=0, length=0) EM::start_proxy(from.signature, to.signature, bufsize, length) end |
.epoll ⇒ Object
#epoll is a harmless no-op in the pure-Ruby implementation. This is intended to ensure that user code behaves properly across different EM implementations.
153 154 |
# File 'lib/em/pure_ruby.rb', line 153 def epoll end |
.epoll=(val) ⇒ Object
Epoll is a no-op for Java. The latest Java versions run epoll when possible in NIO.
150 151 |
# File 'lib/jeventmachine.rb', line 150 def self.epoll= val end |
.epoll? ⇒ Boolean
156 157 158 |
# File 'lib/jeventmachine.rb', line 156 def self.epoll? false end |
.error_handler(cb = nil, &blk) ⇒ Object
Catch-all for errors raised during event loop callbacks.
EM.error_handler{ |e|
puts "Error raised during event loop: #{e.}"
}
1251 1252 1253 1254 1255 1256 1257 |
# File 'lib/eventmachine.rb', line 1251 def self.error_handler cb = nil, &blk if cb or blk @error_handler = cb || blk elsif instance_variable_defined? :@error_handler remove_instance_variable :@error_handler end end |
.event_callback(target, opcode, data) ⇒ Object
:nodoc:
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 |
# File 'lib/eventmachine.rb', line 1338 def self.event_callback conn_binding, opcode, data # :nodoc: # # Changed 27Dec07: Eliminated the hookable error handling. # No one was using it, and it degraded performance significantly. # It's in original_event_callback, which is dead code. # # Changed 25Jul08: Added a partial solution to the problem of exceptions # raised in user-written event-handlers. If such exceptions are not caught, # we must cause the reactor to stop, and then re-raise the exception. # Otherwise, the reactor doesn't stop and it's left on the call stack. # This is partial because we only added it to #unbind, where it's critical # (to keep unbind handlers from being re-entered when a stopping reactor # runs down open connections). It should go on the other calls to user # code, but the performance impact may be too large. # if opcode == ConnectionUnbound if c = @conns.delete( conn_binding ) begin c.unbind rescue @wrapped_exception = $! stop end elsif c = @acceptors.delete( conn_binding ) # no-op else if $! # Bubble user generated errors. @wrapped_exception = $! EM.stop else raise ConnectionNotBound, "recieved ConnectionUnbound for an unknown signature: #{conn_binding}" end end elsif opcode == ConnectionAccepted accep,args,blk = @acceptors[conn_binding] raise NoHandlerForAcceptedConnection unless accep c = accep.new data, *args @conns[data] = c blk and blk.call(c) c # (needed?) ## # The remaining code is a fallback for the pure ruby and java reactors. # In the C++ reactor, these events are handled in the C event_callback() in rubymain.cpp elsif opcode == ConnectionCompleted c = @conns[conn_binding] or raise ConnectionNotBound, "received ConnectionCompleted for unknown signature: #{conn_binding}" c.connection_completed elsif opcode == TimerFired t = @timers.delete( data ) return if t == false # timer cancelled t or raise UnknownTimerFired, "timer data: #{data}" t.call elsif opcode == ConnectionData c = @conns[conn_binding] or raise ConnectionNotBound, "received data #{data} for unknown signature: #{conn_binding}" c.receive_data data elsif opcode == LoopbreakSignalled run_deferred_callbacks elsif opcode == ConnectionNotifyReadable c = @conns[conn_binding] or raise ConnectionNotBound c.notify_readable elsif opcode == ConnectionNotifyWritable c = @conns[conn_binding] or raise ConnectionNotBound c.notify_writable end end |
.fork_reactor(&block) ⇒ Object
fork_reactor forks a new process and calls EM#run inside of it, passing your block. – This implementation is subject to change, especially if we clean up the relationship of EM#run to @reactor_running. Original patch by Aman Gupta.
261 262 263 264 265 266 267 268 269 270 |
# File 'lib/eventmachine.rb', line 261 def self.fork_reactor &block Kernel.fork do if self.reactor_running? self.stop_event_loop self.release_machine self.instance_variable_set( '@reactor_running', false ) end self.run block end end |
.get_connection_count ⇒ Object
247 248 249 |
# File 'lib/jeventmachine.rb', line 247 def self.get_connection_count @em.getConnectionCount end |
.get_max_timer_count ⇒ Object
180 181 182 183 |
# File 'lib/jeventmachine.rb', line 180 def self.get_max_timer_count # harmless no-op in Java. There's no built-in timer limit. @max_timer_count || 100_000 end |
.get_max_timers ⇒ Object
Gets the current maximum number of allowed timers
889 890 891 |
# File 'lib/eventmachine.rb', line 889 def self.get_max_timers get_max_timer_count end |
.get_outbound_data_size(sig) ⇒ Object
#get_outbound_data_size
187 188 189 190 |
# File 'lib/em/pure_ruby.rb', line 187 def get_outbound_data_size sig r = Reactor.instance.get_selectable( sig ) or raise "unknown get_outbound_data_size target" r.get_outbound_data_size end |
.get_peername(sig) ⇒ Object
#get_peername
127 128 129 130 |
# File 'lib/em/pure_ruby.rb', line 127 def get_peername sig selectable = Reactor.instance.get_selectable( sig ) or raise "unknown get_peername target" selectable.get_peername end |
.heartbeat_interval ⇒ Object
Retrieve the heartbeat interval. This is how often EventMachine will check for dead connections that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout. Default is 2 seconds.
1325 1326 1327 |
# File 'lib/eventmachine.rb', line 1325 def self.heartbeat_interval EM::get_heartbeat_interval end |
.heartbeat_interval=(time) ⇒ Object
Set the heartbeat interval. This is how often EventMachine will check for dead connections that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout. Takes a Numeric number of seconds. Default is 2.
1332 1333 1334 |
# File 'lib/eventmachine.rb', line 1332 def self.heartbeat_interval= (time) EM::set_heartbeat_interval time.to_f end |
.initialize_event_machine ⇒ Object
class Connection < com.rubyeventmachine.Connection
def associate_callback_target sig
# No-op for the time being.
end
end
47 48 49 |
# File 'lib/em/pure_ruby.rb', line 47 def initialize_event_machine Reactor.instance.initialize_for_run end |
.invoke_popen(cmd) ⇒ Object
168 169 170 171 |
# File 'lib/jeventmachine.rb', line 168 def self.invoke_popen cmd # TEMPORARILY unsupported until someone figures out how to do it. raise "unsupported on this platform" end |
.is_notify_readable(sig) ⇒ Object
241 242 243 |
# File 'lib/jeventmachine.rb', line 241 def self.is_notify_readable sig @em.isNotifyReadable(sig) end |
.is_notify_writable(sig) ⇒ Object
244 245 246 |
# File 'lib/jeventmachine.rb', line 244 def self.is_notify_writable sig @em.isNotifyWritable(sig) end |
.kqueue ⇒ Object
152 153 |
# File 'lib/jeventmachine.rb', line 152 def self.kqueue end |
.kqueue=(val) ⇒ Object
154 155 |
# File 'lib/jeventmachine.rb', line 154 def self.kqueue= val end |
.kqueue? ⇒ Boolean
159 160 161 |
# File 'lib/jeventmachine.rb', line 159 def self.kqueue? false end |
.library_type ⇒ Object
This is mostly useful for automated tests. Return a distinctive symbol so the caller knows whether he’s dealing with an extension or with a pure-Ruby library.
42 43 44 |
# File 'lib/em/pure_ruby.rb', line 42 def library_type :pure_ruby end |
.next_tick(pr = nil, &block) ⇒ Object
Schedules a proc for execution immediately after the next “turn” through the reactor core. An advanced technique, this can be useful for improving memory management and/or application responsiveness, especially when scheduling large amounts of data for writing to a network connection. TODO, we need a FAQ entry on this subject.
#next_tick takes either a single argument (which must be a Proc) or a block. – This works by adding to the @resultqueue that’s used for #defer. The general idea is that next_tick is used when we want to give the reactor a chance to let other operations run, either to balance the load out more evenly, or to let outbound network buffers drain, or both. So we probably do NOT want to block, and we probably do NOT want to be spinning any threads. A program that uses next_tick but not #defer shouldn’t suffer the penalty of having Ruby threads running. They’re extremely expensive even if they’re just sleeping.
1031 1032 1033 1034 1035 1036 1037 |
# File 'lib/eventmachine.rb', line 1031 def self.next_tick pr=nil, &block raise ArgumentError, "no proc or block given" unless ((pr && pr.respond_to?(:call)) or block) @next_tick_mutex.synchronize do @next_tick_queue << ( pr || block ) end signal_loopbreak if reactor_running? end |
.open_datagram_socket(address, port, handler = nil, *args) ⇒ Object
EventMachine#open_datagram_socket is for support of UDP-based protocols. Its usage is similar to that of EventMachine#start_server. It takes three parameters: an IP address (which must be valid on the machine which executes the method), a port number, and an optional Module name which will handle the data. This method will create a new UDP (datagram) socket and bind it to the address and port that you specify. The normal callbacks (see EventMachine#start_server) will be called as events of interest occur on the newly-created socket, but there are some differences in how they behave.
Connection#receive_data will be called when a datagram packet is received on the socket, but unlike TCP sockets, the message boundaries of the received data will be respected. In other words, if the remote peer sent you a datagram of a particular size, you may rely on Connection#receive_data to give you the exact data in the packet, with the original data length. Also observe that Connection#receive_data may be called with a zero-length data payload, since empty datagrams are permitted in UDP.
Connection#send_data is available with UDP packets as with TCP, but there is an important difference. Because UDP communications are connectionless, there is no implicit recipient for the packets you send. Ordinarily you must specify the recipient for each packet you send. However, EventMachine provides for the typical pattern of receiving a UDP datagram from a remote peer, performing some operation, and then sending one or more packets in response to the same remote peer. To support this model easily, just use Connection#send_data in the code that you supply for Connection:receive_data. EventMachine will provide an implicit return address for any messages sent to Connection#send_data within the context of a Connection#receive_data callback, and your response will automatically go to the correct remote peer. (TODO: Example-code needed!)
Observe that the port number that you supply to EventMachine#open_datagram_socket may be zero. In this case, EventMachine will create a UDP socket that is bound to an ephemeral (not well-known) port. This is not appropriate for servers that must publish a well-known port to which remote peers may send datagrams. But it can be useful for clients that send datagrams to other servers. If you do this, you will receive any responses from the remote servers through the normal Connection#receive_data callback. Observe that you will probably have issues with firewalls blocking the ephemeral port numbers, so this technique is most appropriate for LANs. (TODO: Need an example!)
If you wish to send datagrams to arbitrary remote peers (not necessarily ones that have sent data to which you are responding), then see Connection#send_datagram.
DO NOT call send_data from a datagram socket outside of a #receive_data method. Use #send_datagram. If you do use #send_data outside of a #receive_data method, you’ll get a confusing error because there is no “peer,” as #send_data requires. (Inside of #receive_data, #send_data “fakes” the peer as described above.)
– Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing out that this originally did not take a class but only a module.
852 853 854 855 856 857 858 859 |
# File 'lib/eventmachine.rb', line 852 def self.open_datagram_socket address, port, handler=nil, *args klass = klass_from_handler(Connection, handler, *args) s = open_udp_socket address, port.to_i c = klass.new s, *args @conns[s] = c block_given? and yield c c end |
.open_keyboard(handler = nil, *args) ⇒ Object
(Experimental)
1130 1131 1132 1133 1134 1135 1136 1137 1138 |
# File 'lib/eventmachine.rb', line 1130 def self.open_keyboard handler=nil, *args klass = klass_from_handler(Connection, handler, *args) s = read_keyboard c = klass.new s, *args @conns[s] = c block_given? and yield c c end |
.open_udp_socket(server, port) ⇒ Object
Currently a no-op for Java.
133 134 135 |
# File 'lib/em/pure_ruby.rb', line 133 def open_udp_socket host, port EvmaUDPSocket.create(host, port).uuid end |
.popen(cmd, handler = nil, *args) {|c| ... } ⇒ Object
Run an external process. This does not currently work on Windows.
module RubyCounter
def post_init
# count up to 5
send_data "5\n"
end
def receive_data data
puts "ruby sent me: #{data}"
end
def unbind
puts "ruby died with exit status: #{get_status.exitstatus}"
end
end
EM.run{
EM.popen("ruby -e' $stdout.sync = true; gets.to_i.times{ |i| puts i+1; sleep 1 } '", RubyCounter)
}
Also see EventMachine::DeferrableChildProcess and EventMachine.system – At this moment, it’s only available on Unix. Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 |
# File 'lib/eventmachine.rb', line 1100 def self.popen cmd, handler=nil, *args klass = klass_from_handler(Connection, handler, *args) w = Shellwords::shellwords( cmd ) w.unshift( w.first ) if w.first s = invoke_popen( w ) c = klass.new s, *args @conns[s] = c yield(c) if block_given? c end |
.reactor_running? ⇒ Boolean
Tells you whether the EventMachine reactor loop is currently running. Returns true or false. Useful when writing libraries that want to run event-driven code, but may be running in programs that are already event-driven. In such cases, if EventMachine#reactor_running? returns false, your code can invoke EventMachine#run and run your application code inside the block passed to that method. If EventMachine#reactor_running? returns true, just execute your event-aware code.
This method is necessary because calling EventMachine#run inside of another call to EventMachine#run generates a fatal error.
1122 1123 1124 |
# File 'lib/eventmachine.rb', line 1122 def self.reactor_running? (@reactor_running || false) end |
.reactor_thread? ⇒ Boolean
Returns true if the calling thread is the same thread as the reactor.
240 241 242 |
# File 'lib/eventmachine.rb', line 240 def self.reactor_thread? Thread.current == @reactor_thread end |
.read_keyboard ⇒ Object
#read_keyboard
194 195 196 |
# File 'lib/em/pure_ruby.rb', line 194 def read_keyboard EvmaKeyboard.open.uuid end |
.reconnect(server, port, handler) ⇒ Object
Connect to a given host/port and re-use the provided EventMachine::Connection instance – Observe, the test for already-connected FAILS if we call a reconnect inside post_init, because we haven’t set up the connection in @conns by that point. RESIST THE TEMPTATION to “fix” this problem by redefining the behavior of post_init.
Changed 22Nov06: if called on an already-connected handler, just return the handler and do nothing more. Originally this condition raised an exception. We may want to change it yet again and call the block, if any.
756 757 758 759 760 761 762 763 764 765 766 |
# File 'lib/eventmachine.rb', line 756 def self.reconnect server, port, handler # :nodoc: raise "invalid handler" unless handler.respond_to?(:connection_completed) #raise "still connected" if @conns.has_key?(handler.signature) return handler if @conns.has_key?(handler.signature) s = connect_server server, port handler.signature = s @conns[s] = handler block_given? and yield handler handler end |
.release_machine ⇒ Object
release_machine. Probably a no-op.
65 66 |
# File 'lib/em/pure_ruby.rb', line 65 def release_machine end |
.run(blk = nil, tail = nil, &block) ⇒ Object
EventMachine::run initializes and runs an event loop. This method only returns if user-callback code calls stop_event_loop. Use the supplied block to define your clients and servers. The block is called by EventMachine::run immediately after initializing its internal event loop but before running the loop. Therefore this block is the right place to call start_server if you want to accept connections from remote clients.
For programs that are structured as servers, it’s usually appropriate to start an event loop by calling EventMachine::run, and let it run forever. It’s also possible to use EventMachine::run to make a single client-connection to a remote server, process the data flow from that single connection, and then call stop_event_loop to force EventMachine::run to return. Your program will then continue from the point immediately following the call to EventMachine::run.
You can of course do both client and servers simultaneously in the same program. One of the strengths of the event-driven programming model is that the handling of network events on many different connections will be interleaved, and scheduled according to the actual events themselves. This maximizes efficiency.
Server usage example
See EventMachine.start_server
Client usage example
See EventMachine.connect
– Obsoleted the use_threads mechanism. 25Nov06: Added the begin/ensure block. We need to be sure that release_machine gets called even if an exception gets thrown within any of the user code that the event loop runs. The best way to see this is to run a unit test with two functions, each of which calls EventMachine#run and each of which throws something inside of #run. Without the ensure, the second test will start without release_machine being called and will immediately throw a C++ runtime error.
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'lib/eventmachine.rb', line 175 def self.run blk=nil, tail=nil, &block @tails ||= [] tail and @tails.unshift(tail) if reactor_running? (b = blk || block) and b.call # next_tick(b) else @conns = {} @acceptors = {} @timers = {} @wrapped_exception = nil @next_tick_queue ||= [] begin @reactor_running = true initialize_event_machine (b = blk || block) and add_timer(0, b) if @next_tick_queue && !@next_tick_queue.empty? add_timer(0) { signal_loopbreak } end @reactor_thread = Thread.current run_machine ensure until @tails.empty? @tails.pop.call end begin release_machine ensure if @threadpool @threadpool.each { |t| t.exit } @threadpool.each do |t| next unless t.alive? # ruby 1.9 has no kill! t.respond_to?(:kill!) ? t.kill! : t.kill end @threadqueue = nil @resultqueue = nil @threadpool = nil end @next_tick_queue = [] end @reactor_running = false @reactor_thread = nil end raise @wrapped_exception if @wrapped_exception end end |
.run_block(&block) ⇒ Object
Sugars a common use case. Will pass the given block to #run, but will terminate the reactor loop and exit the function as soon as the code in the block completes. (Normally, #run keeps running indefinitely, even after the block supplied to it finishes running, until user code calls #stop.)
231 232 233 234 235 236 237 |
# File 'lib/eventmachine.rb', line 231 def self.run_block &block pr = proc { block.call EventMachine::stop } run(&pr) end |
.run_deferred_callbacks ⇒ Object
– The is the responder for the loopback-signalled event. It can be fired either by code running on a separate thread (EM#defer) or on the main thread (EM#next_tick). It will often happen that a next_tick handler will reschedule itself. We consume a copy of the tick queue so that tick events scheduled by tick events have to wait for the next pass through the reactor core.
925 926 927 928 929 930 931 932 933 934 935 |
# File 'lib/eventmachine.rb', line 925 def self.run_deferred_callbacks # :nodoc: until (@resultqueue ||= []).empty? result,cback = @resultqueue.pop cback.call result if cback end @next_tick_mutex.synchronize do jobs, @next_tick_queue = @next_tick_queue, [] jobs end.each { |j| j.call } end |
.run_machine ⇒ Object
run_machine
60 61 62 |
# File 'lib/em/pure_ruby.rb', line 60 def run_machine Reactor.instance.run end |
.schedule(*a, &b) ⇒ Object
Runs the given callback on the reactor thread, or immediately if called from the reactor thread. Accepts the same arguments as EM::Callback
246 247 248 249 250 251 252 253 |
# File 'lib/eventmachine.rb', line 246 def self.schedule(*a, &b) cb = Callback(*a, &b) if reactor_running? && reactor_thread? cb.call else next_tick { cb.call } end end |
.send_data(sig, data, length) ⇒ Object
#send_data
84 85 86 87 |
# File 'lib/em/pure_ruby.rb', line 84 def send_data target, data, datalength selectable = Reactor.instance.get_selectable( target ) or raise "unknown send_data target" selectable.send_data data end |
.send_datagram(sig, data, length, address, port) ⇒ Object
#send_datagram. This is currently only for UDP! We need to make it work with unix-domain sockets as well.
139 140 141 142 |
# File 'lib/em/pure_ruby.rb', line 139 def send_datagram target, data, datalength, host, port selectable = Reactor.instance.get_selectable( target ) or raise "unknown send_data target" selectable.send_datagram data, Socket::pack_sockaddr_in(port, host) end |
.send_file_data(sig, filename) ⇒ Object
#send_file_data
173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/em/pure_ruby.rb', line 173 def send_file_data sig, filename sz = File.size(filename) raise "file too large" if sz > 32*1024 data = begin File.read filename rescue "" end send_data sig, data, data.length end |
.set_comm_inactivity_timeout(sig, interval) ⇒ Object
#set_comm_inactivity_timeout
200 201 202 203 |
# File 'lib/em/pure_ruby.rb', line 200 def set_comm_inactivity_timeout sig, tm r = Reactor.instance.get_selectable( sig ) or raise "unknown set_comm_inactivity_timeout target" r.set_inactivity_timeout tm end |
.set_descriptor_table_size(n_descriptors = nil) ⇒ Object
Sets the maximum number of file or socket descriptors that your process may open. You can pass this method an integer specifying the new size of the descriptor table. Returns the new descriptor-table size, which may be less than the number you requested. If you call this method with no arguments, it will simply return the current size of the descriptor table without attempting to change it.
The new limit on open descriptors ONLY applies to sockets and other descriptors that belong to EventMachine. It has NO EFFECT on the number of descriptors you can create in ordinary Ruby code.
Not available on all platforms. Increasing the number of descriptors beyond its default limit usually requires superuser privileges. (See #set_effective_user for a way to drop superuser privileges while your program is running.)
1070 1071 1072 |
# File 'lib/eventmachine.rb', line 1070 def self.set_descriptor_table_size n_descriptors=nil EventMachine::set_rlimit_nofile n_descriptors end |
.set_effective_user(username) ⇒ Object
A wrapper over the setuid system call. Particularly useful when opening a network server on a privileged port because you can use this call to drop privileges after opening the port. Also very useful after a call to #set_descriptor_table_size, which generally requires that you start your process with root privileges.
This method has no effective implementation on Windows or in the pure-Ruby implementation of EventMachine. Call #set_effective_user by passing it a string containing the effective name of the user whose privilege-level your process should attain. This method is intended for use in enforcing security requirements, consequently it will throw a fatal error and end your program if it fails.
1051 1052 1053 |
# File 'lib/eventmachine.rb', line 1051 def self.set_effective_user username EventMachine::setuid_string username end |
.set_max_timer_count(num) ⇒ Object
#set_max_timer_count is a harmless no-op in pure Ruby, which doesn’t have a built-in limit on the number of available timers.
169 170 |
# File 'lib/em/pure_ruby.rb', line 169 def set_max_timer_count n end |
.set_max_timers(ct) ⇒ Object
Sets the maximum number of timers and periodic timers that may be outstanding at any given time. You only need to call #set_max_timers if you need more than the default number of timers, which on most platforms is 1000. Call this method before calling EventMachine#run.
883 884 885 |
# File 'lib/eventmachine.rb', line 883 def self.set_max_timers ct set_max_timer_count ct end |
.set_notify_readable(sig, mode) ⇒ Object
234 235 236 |
# File 'lib/jeventmachine.rb', line 234 def self.set_notify_readable sig, mode @em.setNotifyReadable(sig, mode) end |
.set_notify_writable(sig, mode) ⇒ Object
237 238 239 |
# File 'lib/jeventmachine.rb', line 237 def self.set_notify_writable sig, mode @em.setNotifyWritable(sig, mode) end |
.set_quantum(mills) ⇒ Object
For advanced users. This function sets the default timer granularity, which by default is slightly smaller than 100 milliseconds. Call this function to set a higher or lower granularity. The function affects the behavior of #add_timer and #add_periodic_timer. Most applications will not need to call this function.
The argument is a number of milliseconds. Avoid setting the quantum to very low values because that may reduce performance under some extreme conditions. We recommend that you not set a quantum lower than 10.
You may only call this function while an EventMachine loop is running (that is, after a call to EventMachine#run and before a subsequent call to EventMachine#stop).
874 875 876 |
# File 'lib/eventmachine.rb', line 874 def self.set_quantum mills set_timer_quantum mills.to_i end |
.set_rlimit_nofile(n_descriptors) ⇒ Object
#set_rlimit_nofile is a no-op in the pure-Ruby implementation. We simply return Ruby’s built-in per-process file-descriptor limit.
163 164 165 |
# File 'lib/em/pure_ruby.rb', line 163 def set_rlimit_nofile n 1024 end |
.set_timer_quantum(q) ⇒ Object
#set_timer_quantum in milliseconds. The underlying Reactor function wants a (possibly fractional) number of seconds.
147 148 149 |
# File 'lib/em/pure_ruby.rb', line 147 def set_timer_quantum interval Reactor.instance.set_timer_quantum(( 1.0 * interval) / 1000.0) end |
.signal_loopbreak ⇒ Object
#signal_loopbreak
122 123 124 |
# File 'lib/em/pure_ruby.rb', line 122 def signal_loopbreak Reactor.instance.signal_loopbreak end |
.spawn(&block) ⇒ Object
Spawn an erlang-style process
72 73 74 75 76 |
# File 'lib/em/spawnable.rb', line 72 def self.spawn &block s = SpawnedProcess.new s.set_receiver block s end |
.spawn_threadpool ⇒ Object
:nodoc:
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 |
# File 'lib/eventmachine.rb', line 993 def self.spawn_threadpool # :nodoc: until @threadpool.size == @threadpool_size.to_i thread = Thread.new do Thread.current.abort_on_exception = true while true op, cback = *@threadqueue.pop result = op.call @resultqueue << [result, cback] EventMachine.signal_loopbreak end end @threadpool << thread end end |
.ssl? ⇒ Boolean
#ssl? is not implemented for pure-Ruby implementation
157 158 159 |
# File 'lib/em/pure_ruby.rb', line 157 def ssl? false end |
.start_server(server, port = nil, handler = nil, *args, &block) ⇒ Object
EventMachine::start_server initiates a TCP server (socket acceptor) on the specified IP address and port. The IP address must be valid on the machine where the program runs, and the process must be privileged enough to listen on the specified port (on Unix-like systems, superuser privileges are usually required to listen on any port lower than 1024). Only one listener may be running on any given address/port combination. start_server will fail if the given address and port are already listening on the machine, either because of a prior call to start_server or some unrelated process running on the machine. If start_server succeeds, the new network listener becomes active immediately and starts accepting connections from remote peers, and these connections generate callback events that are processed by the code specified in the handler parameter to start_server.
The optional handler which is passed to start_server is the key to EventMachine’s ability to handle particular network protocols. The handler parameter passed to start_server must be a Ruby Module that you must define. When the network server that is started by start_server accepts a new connection, it instantiates a new object of an anonymous class that is inherited from EventMachine::Connection, into which the methods from your handler have been mixed. Your handler module may redefine any of the methods in EventMachine::Connection in order to implement the specific behavior of the network protocol.
Callbacks invoked in response to network events always take place within the execution context of the object derived from EventMachine::Connection extended by your handler module. There is one object per connection, and all of the callbacks invoked for a particular connection take the form of instance methods called against the corresponding EventMachine::Connection object. Therefore, you are free to define whatever instance variables you wish, in order to contain the per-connection state required by the network protocol you are implementing.
start_server is often called inside the block passed to EventMachine::run, but it can be called from any EventMachine callback. start_server will fail unless the EventMachine event loop is currently running (which is why it’s often called in the block suppled to EventMachine::run).
You may call start_server any number of times to start up network listeners on different address/port combinations. The servers will all run simultaneously. More interestingly, each individual call to start_server can specify a different handler module and thus implement a different network protocol from all the others.
Usage example
Here is an example of a server that counts lines of input from the remote peer and sends back the total number of lines received, after each line. Try the example with more than one client connection opened via telnet, and you will see that the line count increments independently on each of the client connections. Also very important to note, is that the handler for the receive_data function, which our handler redefines, may not assume that the data it receives observes any kind of message boundaries. Also, to use this example, be sure to change the server and port parameters to the start_server call to values appropriate for your environment.
require 'rubygems'
require 'eventmachine'
module LineCounter
MaxLinesPerConnection = 10
def post_init
puts "Received a new connection"
@data_received = ""
@line_count = 0
end
def receive_data data
@data_received << data
while @data_received.slice!( /^[^\n]*[\n]/m )
@line_count += 1
send_data "received #{@line_count} lines so far\r\n"
@line_count == MaxLinesPerConnection and close_connection_after_writing
end
end
end
EventMachine::run {
host,port = "192.168.0.100", 8090
EventMachine::start_server host, port, LineCounter
puts "Now accepting connections on address #{host}, port #{port}..."
EventMachine::add_periodic_timer( 10 ) { $stderr.write "*" }
}
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
# File 'lib/eventmachine.rb', line 497 def self.start_server server, port=nil, handler=nil, *args, &block begin port = Integer(port) rescue ArgumentError, TypeError # there was no port, so server must be a unix domain socket # the port argument is actually the handler, and the handler is one of the args args.unshift handler if handler handler = port port = nil end if port klass = klass_from_handler(Connection, handler, *args) s = if port start_tcp_server server, port else start_unix_server server end @acceptors[s] = [klass,args,block] s end |
.start_tcp_server(server, port) ⇒ Object
#start_tcp_server
99 100 101 102 |
# File 'lib/em/pure_ruby.rb', line 99 def start_tcp_server host, port (s = EvmaTCPServer.start_server host, port) or raise "no acceptor" s.uuid end |
.start_tls(sig) ⇒ Object
134 135 136 |
# File 'lib/jeventmachine.rb', line 134 def self.start_tls sig @em.startTls sig end |
.start_unix_domain_server(filename, *args, &block) ⇒ Object
Start a Unix-domain server
Note that this is an alias for EventMachine::start_server, which can be used to start both TCP and Unix-domain servers
533 534 535 |
# File 'lib/eventmachine.rb', line 533 def self.start_unix_domain_server filename, *args, &block start_server filename, *args, &block end |
.start_unix_server(filename) ⇒ Object
#start_unix_server
111 112 113 114 |
# File 'lib/em/pure_ruby.rb', line 111 def start_unix_server chain (s = EvmaUNIXServer.start_server chain) or raise "no acceptor" s.uuid end |
.stop ⇒ Object
#stop
69 70 71 |
# File 'lib/em/pure_ruby.rb', line 69 def stop Reactor.instance.stop end |
.stop_event_loop ⇒ Object
stop_event_loop may called from within a callback method while EventMachine’s processing loop is running. It causes the processing loop to stop executing, which will cause all open connections and accepting servers to be run down and closed. Callbacks for connection-termination will be called as part of the processing of stop_event_loop. (There currently is no option to panic-stop the loop without closing connections.) When all of this processing is complete, the call to EventMachine::run which started the processing loop will return and program flow will resume from the statement following EventMachine::run call.
Usage example
require 'rubygems'
require 'eventmachine'
module Redmond
def post_init
puts "We're sending a dumb HTTP request to the remote peer."
send_data "GET / HTTP/1.1\r\nHost: www.microsoft.com\r\n\r\n"
end
def receive_data data
puts "We received #{data.length} bytes from the remote peer."
puts "We're going to stop the event loop now."
EventMachine::stop_event_loop
end
def unbind
puts "A connection has terminated."
end
end
puts "We're starting the event loop now."
EventMachine::run {
EventMachine::connect "www.microsoft.com", 80, Redmond
}
puts "The event loop has stopped."
This program will produce approximately the following output:
We're starting the event loop now.
We're sending a dumb HTTP request to the remote peer.
We received 1440 bytes from the remote peer.
We're going to stop the event loop now.
A connection has terminated.
The event loop has stopped.
407 408 409 |
# File 'lib/eventmachine.rb', line 407 def self.stop_event_loop EventMachine::stop end |
.stop_server(signature) ⇒ Object
Stop a TCP server socket that was started with EventMachine#start_server. – Requested by Kirk Haines. TODO, this isn’t OOP enough. We ought somehow to have #start_server return an object that has a close or a stop method on it.
525 526 527 |
# File 'lib/eventmachine.rb', line 525 def self.stop_server signature EventMachine::stop_tcp_server signature end |
.stop_tcp_server(sig) ⇒ Object
#stop_tcp_server
105 106 107 108 |
# File 'lib/em/pure_ruby.rb', line 105 def stop_tcp_server sig s = Reactor.instance.get_selectable(sig) s.schedule_close end |
.system(cmd, *args, &cb) ⇒ Object
EM::system is a simple wrapper for EM::popen. It is similar to Kernel::system, but requires a single string argument for the command and performs no shell expansion.
The block or proc passed to EM::system is called with two arguments: the output generated by the command, and a Process::Status that contains information about the command’s execution.
EM.run{
EM.system('ls'){ |output,status| puts output if status.exitstatus == 0 }
}
You can also supply an additional proc to send some data to the process:
EM.run{
EM.system('sh', proc{ |process|
process.send_data("echo hello\n")
process.send_data("exit\n")
}, proc{ |out,status|
puts(out)
})
}
Like EventMachine.popen, EventMachine.system currently does not work on windows. It returns the pid of the spawned process.
108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/em/processes.rb', line 108 def EventMachine::system cmd, *args, &cb cb ||= args.pop if args.last.is_a? Proc init = args.pop if args.last.is_a? Proc # merge remaining arguments into the command cmd = ([cmd] + args.map{|a|a.to_s.dump}).join(' ') EM.get_subprocess_pid(EM.popen(cmd, SystemCmd, cb) do |c| init[c] if init end.signature) end |
.tick_loop(*a, &b) ⇒ Object
Creates and immediately starts an EventMachine::TickLoop
3 4 5 |
# File 'lib/em/tick_loop.rb', line 3 def self.tick_loop(*a, &b) TickLoop.new(*a, &b).start end |
.watch(io, handler = nil, *args, &blk) ⇒ Object
EventMachine::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
Usage Example
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
EM.run{
$sock = TCPSocket.new('site.com', 80)
$sock.write("GET / HTTP/1.0\r\n\r\n")
conn = EM.watch $sock, SimpleHttpClient
conn.notify_readable = true
}
– Thanks to Riham Aldakkak (eSpace Technologies) for the initial patch
707 708 709 |
# File 'lib/eventmachine.rb', line 707 def EventMachine::watch io, handler=nil, *args, &blk attach_io io, true, handler, *args, &blk end |
.watch_file(filename, handler = nil, *args) ⇒ Object
EventMachine’s file monitoring API. Currently supported are the following events on individual files, using inotify on Linux systems, and kqueue for OSX/BSD:
-
File modified (written to)
-
File moved/renamed
-
File deleted
EventMachine::watch_file takes a filename and a handler Module containing your custom callback methods. This will setup the low level monitoring on the specified file, and create a new EventMachine::FileWatch object with your Module mixed in. FileWatch is a subclass of EM::Connection, so callbacks on this object work in the familiar way. The callbacks that will be fired by EventMachine are:
-
file_modified
-
file_moved
-
file_deleted
You can access the filename being monitored from within this object using FileWatch#path.
When a file is deleted, FileWatch#stop_watching will be called after your file_deleted callback, to clean up the underlying monitoring and remove EventMachine’s reference to the now-useless FileWatch. This will in turn call unbind, if you wish to use it.
The corresponding system-level Errno will be raised when attempting to monitor non-existent files, files with wrong permissions, or if an error occurs dealing with inotify/kqueue.
Usage example:
Make sure we have a file to monitor:
$ echo "bar" > /tmp/foo
module Handler
def file_modified
puts "#{path} modified"
end
def file_moved
puts "#{path} moved"
end
def file_deleted
puts "#{path} deleted"
end
def unbind
puts "#{path} monitoring ceased"
end
end
EM.kqueue = true if EM.kqueue? # file watching requires kqueue on OSX
EM.run {
EM.watch_file("/tmp/foo", Handler)
}
$ echo "baz" >> /tmp/foo => "/tmp/foo modified"
$ mv /tmp/foo /tmp/oof => "/tmp/foo moved"
$ rm /tmp/oof => "/tmp/foo deleted"
=> "/tmp/foo monitoring ceased"
Note that we have not implemented the ability to pick up on the new filename after a rename. Calling #path will always return the filename you originally used.
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 |
# File 'lib/eventmachine.rb', line 1202 def self.watch_file(filename, handler=nil, *args) klass = klass_from_handler(FileWatch, handler, *args) s = EM::watch_filename(filename) c = klass.new s, *args # we have to set the path like this because of how Connection.new works c.instance_variable_set("@path", filename) @conns[s] = c block_given? and yield c c end |
.watch_process(pid, handler = nil, *args) ⇒ Object
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 |
# File 'lib/eventmachine.rb', line 1231 def self.watch_process(pid, handler=nil, *args) pid = pid.to_i klass = klass_from_handler(ProcessWatch, handler, *args) s = EM::watch_pid(pid) c = klass.new s, *args # we have to set the path like this because of how Connection.new works c.instance_variable_set("@pid", pid) @conns[s] = c block_given? and yield c c end |
.yield(&block) ⇒ Object
:nodoc:
78 79 80 |
# File 'lib/em/spawnable.rb', line 78 def self.yield &block # :nodoc: return YieldBlockFromSpawnedProcess.new( block, false ) end |
.yield_and_notify(&block) ⇒ Object
:nodoc:
82 83 84 |
# File 'lib/em/spawnable.rb', line 82 def self.yield_and_notify &block # :nodoc: return YieldBlockFromSpawnedProcess.new( block, true ) end |