eventmachine 1.0.0.beta.3-java → 1.0.0.beta.4-java

Sign up to get free protection for your applications and to get access to all the features.
Files changed (97) hide show
  1. data/.gitignore +5 -0
  2. data/.yardopts +5 -1
  3. data/{docs/GNU → GNU} +0 -0
  4. data/Gemfile +1 -0
  5. data/{docs/COPYING → LICENSE} +0 -0
  6. data/README.md +109 -0
  7. data/Rakefile +8 -0
  8. data/docs/DocumentationGuidesIndex.md +27 -0
  9. data/docs/GettingStarted.md +521 -0
  10. data/docs/{ChangeLog → old/ChangeLog} +0 -0
  11. data/docs/{DEFERRABLES → old/DEFERRABLES} +0 -0
  12. data/docs/{EPOLL → old/EPOLL} +0 -0
  13. data/docs/{INSTALL → old/INSTALL} +0 -0
  14. data/docs/{KEYBOARD → old/KEYBOARD} +0 -0
  15. data/docs/{LEGAL → old/LEGAL} +0 -0
  16. data/docs/{LIGHTWEIGHT_CONCURRENCY → old/LIGHTWEIGHT_CONCURRENCY} +0 -0
  17. data/docs/{PURE_RUBY → old/PURE_RUBY} +0 -0
  18. data/docs/{RELEASE_NOTES → old/RELEASE_NOTES} +0 -0
  19. data/docs/{SMTP → old/SMTP} +0 -0
  20. data/docs/{SPAWNED_PROCESSES → old/SPAWNED_PROCESSES} +0 -0
  21. data/docs/{TODO → old/TODO} +0 -0
  22. data/eventmachine.gemspec +5 -2
  23. data/examples/guides/getting_started/01_eventmachine_echo_server.rb +18 -0
  24. data/examples/guides/getting_started/02_eventmachine_echo_server_that_recognizes_exit_command.rb +22 -0
  25. data/examples/guides/getting_started/03_simple_chat_server.rb +149 -0
  26. data/examples/guides/getting_started/04_simple_chat_server_step_one.rb +27 -0
  27. data/examples/guides/getting_started/05_simple_chat_server_step_two.rb +43 -0
  28. data/examples/guides/getting_started/06_simple_chat_server_step_three.rb +98 -0
  29. data/examples/guides/getting_started/07_simple_chat_server_step_four.rb +121 -0
  30. data/examples/guides/getting_started/08_simple_chat_server_step_five.rb +141 -0
  31. data/examples/{ex_channel.rb → old/ex_channel.rb} +3 -3
  32. data/examples/{ex_queue.rb → old/ex_queue.rb} +0 -0
  33. data/examples/{ex_tick_loop_array.rb → old/ex_tick_loop_array.rb} +0 -0
  34. data/examples/{ex_tick_loop_counter.rb → old/ex_tick_loop_counter.rb} +0 -0
  35. data/examples/{helper.rb → old/helper.rb} +0 -0
  36. data/ext/cmain.cpp +3 -3
  37. data/ext/ed.cpp +90 -15
  38. data/ext/ed.h +5 -5
  39. data/ext/em.cpp +59 -65
  40. data/ext/em.h +12 -2
  41. data/ext/extconf.rb +3 -3
  42. data/ext/pipe.cpp +2 -2
  43. data/ext/project.h +1 -1
  44. data/ext/rubymain.cpp +48 -3
  45. data/ext/ssl.cpp +5 -0
  46. data/java/src/com/rubyeventmachine/EmReactor.java +2 -2
  47. data/lib/em/buftok.rb +35 -63
  48. data/lib/em/callback.rb +43 -11
  49. data/lib/em/channel.rb +21 -14
  50. data/lib/em/completion.rb +304 -0
  51. data/lib/em/connection.rb +339 -209
  52. data/lib/em/deferrable.rb +4 -0
  53. data/lib/em/deferrable/pool.rb +2 -0
  54. data/lib/em/file_watch.rb +37 -18
  55. data/lib/em/iterator.rb +42 -42
  56. data/lib/em/pool.rb +146 -0
  57. data/lib/em/process_watch.rb +5 -4
  58. data/lib/em/processes.rb +8 -4
  59. data/lib/em/protocols/httpclient.rb +22 -11
  60. data/lib/em/protocols/httpclient2.rb +15 -5
  61. data/lib/em/protocols/line_protocol.rb +2 -1
  62. data/lib/em/protocols/memcache.rb +17 -9
  63. data/lib/em/protocols/object_protocol.rb +2 -1
  64. data/lib/em/protocols/postgres3.rb +8 -9
  65. data/lib/em/protocols/smtpclient.rb +19 -11
  66. data/lib/em/protocols/smtpserver.rb +1 -1
  67. data/lib/em/protocols/stomp.rb +8 -6
  68. data/lib/em/protocols/tcptest.rb +3 -2
  69. data/lib/em/pure_ruby.rb +212 -208
  70. data/lib/em/queue.rb +22 -13
  71. data/lib/em/resolver.rb +70 -64
  72. data/lib/em/spawnable.rb +6 -3
  73. data/lib/em/streamer.rb +33 -45
  74. data/lib/em/threaded_resource.rb +90 -0
  75. data/lib/em/timers.rb +6 -2
  76. data/lib/em/version.rb +1 -1
  77. data/lib/eventmachine.rb +538 -602
  78. data/lib/jeventmachine.rb +22 -1
  79. data/tasks/package.rake +13 -3
  80. data/tasks/test.rake +1 -0
  81. data/tests/em_test_helper.rb +12 -3
  82. data/tests/test_completion.rb +177 -0
  83. data/tests/test_epoll.rb +2 -2
  84. data/tests/test_httpclient.rb +9 -9
  85. data/tests/test_httpclient2.rb +11 -9
  86. data/tests/test_ltp.rb +2 -10
  87. data/tests/test_pool.rb +128 -0
  88. data/tests/test_processes.rb +20 -2
  89. data/tests/test_queue.rb +8 -0
  90. data/tests/test_resolver.rb +1 -1
  91. data/tests/test_set_sock_opt.rb +37 -0
  92. data/tests/test_shutdown_hooks.rb +23 -0
  93. data/tests/test_threaded_resource.rb +53 -0
  94. data/tests/test_unbind_reason.rb +31 -0
  95. metadata +87 -45
  96. data/README +0 -81
  97. data/tasks/doc.rake +0 -30
data/lib/em/timers.rb CHANGED
@@ -20,6 +20,7 @@ module EventMachine
20
20
 
21
21
  # Creates a periodic timer
22
22
  #
23
+ # @example
23
24
  # n = 0
24
25
  # timer = EventMachine::PeriodicTimer.new(5) do
25
26
  # puts "the time is #{Time.now}"
@@ -44,10 +45,13 @@ module EventMachine
44
45
  # Fire the timer every interval seconds
45
46
  attr_accessor :interval
46
47
 
47
- def schedule # :nodoc:
48
+ # @private
49
+ def schedule
48
50
  EventMachine::add_timer @interval, @work
49
51
  end
50
- def fire # :nodoc:
52
+
53
+ # @private
54
+ def fire
51
55
  unless @cancelled
52
56
  @code.call
53
57
  schedule
data/lib/em/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module EventMachine
2
- VERSION = "1.0.0.beta.3"
2
+ VERSION = "1.0.0.beta.4"
3
3
  end
data/lib/eventmachine.rb CHANGED
@@ -13,6 +13,7 @@ else
13
13
  end
14
14
 
15
15
  require 'em/version'
16
+ require 'em/pool'
16
17
  require 'em/deferrable'
17
18
  require 'em/future'
18
19
  require 'em/streamer'
@@ -30,154 +31,132 @@ require 'em/file_watch'
30
31
  require 'em/process_watch'
31
32
  require 'em/tick_loop'
32
33
  require 'em/resolver'
34
+ require 'em/completion'
35
+ require 'em/threaded_resource'
33
36
 
34
37
  require 'shellwords'
35
38
  require 'thread'
36
39
  require 'resolv'
37
40
 
38
- # == Introduction
39
- # EventMachine provides a fast, lightweight framework for implementing
40
- # Ruby programs that can use the network to communicate with other
41
- # processes. Using EventMachine, Ruby programmers can easily connect
42
- # to remote servers and act as servers themselves. EventMachine does not
43
- # supplant the Ruby IP libraries. It does provide an alternate technique
44
- # for those applications requiring better performance, scalability,
45
- # and discipline over the behavior of network sockets, than is easily
46
- # obtainable using the built-in libraries, especially in applications
47
- # which are structurally well-suited for the event-driven programming model.
41
+ # Top-level EventMachine namespace. If you are looking for EventMachine examples, see {file:docs/GettingStarted.md EventMachine tutorial}.
48
42
  #
49
- # EventMachine provides a perpetual event-loop which your programs can
50
- # start and stop. Within the event loop, TCP network connections are
51
- # initiated and accepted, based on EventMachine methods called by your
52
- # program. You also define callback methods which are called by EventMachine
53
- # when events of interest occur within the event-loop.
43
+ # ## Key methods ##
44
+ # ### Starting and stopping the event loop ###
54
45
  #
55
- # User programs will be called back when the following events occur:
56
- # * When the event loop accepts network connections from remote peers
57
- # * When data is received from network connections
58
- # * When connections are closed, either by the local or the remote side
59
- # * When user-defined timers expire
46
+ # * {EventMachine.run}
47
+ # * {EventMachine.stop_event_loop}
60
48
  #
61
- # == Usage example
49
+ # ### Implementing clients ###
62
50
  #
63
- # Here's a fully-functional echo server implemented in EventMachine:
51
+ # * {EventMachine.connect}
64
52
  #
65
- # require 'eventmachine'
53
+ # ### Implementing servers ###
66
54
  #
67
- # module EchoServer
68
- # def post_init
69
- # puts "-- someone connected to the echo server!"
70
- # end
55
+ # * {EventMachine.start_server}
71
56
  #
72
- # def receive_data data
73
- # send_data ">>>you sent: #{data}"
74
- # close_connection if data =~ /quit/i
75
- # end
57
+ # ### Working with timers ###
76
58
  #
77
- # def unbind
78
- # puts "-- someone disconnected from the echo server!"
79
- # end
80
- # end
59
+ # * {EventMachine.add_timer}
60
+ # * {EventMachine.add_periodic_timer}
61
+ # * {EventMachine.cancel_timer}
81
62
  #
82
- # EventMachine::run {
83
- # EventMachine::start_server "127.0.0.1", 8081, EchoServer
84
- # }
63
+ # ### Working with blocking tasks ###
85
64
  #
86
- # What's going on here? Well, we have defined the module EchoServer to
87
- # implement the semantics of the echo protocol (more about that shortly).
88
- # The last three lines invoke the event-machine itself, which runs forever
89
- # unless one of your callbacks terminates it. The block that you supply
90
- # to EventMachine::run contains code that runs immediately after the event
91
- # machine is initialized and before it starts looping. This is the place
92
- # to open up a TCP server by specifying the address and port it will listen
93
- # on, together with the module that will process the data.
94
- #
95
- # Our EchoServer is extremely simple as the echo protocol doesn't require
96
- # much work. Basically you want to send back to the remote peer whatever
97
- # data it sends you. We'll dress it up with a little extra text to make it
98
- # interesting. Also, we'll close the connection in case the received data
99
- # contains the word "quit."
100
- #
101
- # So what about this module EchoServer? Well, whenever a network connection
102
- # (either a client or a server) starts up, EventMachine instantiates an anonymous
103
- # class, that your module has been mixed into. Exactly one of these class
104
- # instances is created for each connection. Whenever an event occurs on a
105
- # given connection, its corresponding object automatically calls specific
106
- # instance methods which your module may redefine. The code in your module
107
- # always runs in the context of a class instance, so you can create instance
108
- # variables as you wish and they will be carried over to other callbacks
109
- # made on that same connection.
110
- #
111
- # Looking back up at EchoServer, you can see that we've defined the method
112
- # receive_data which (big surprise) is called whenever data has been received
113
- # from the remote end of the connection. Very simple. We get the data
114
- # (a String object) and can do whatever we wish with it. In this case,
115
- # we use the method send_data to return the received data to the caller,
116
- # with some extra text added in. And if the user sends the word "quit,"
117
- # we'll close the connection with (naturally) close_connection.
118
- # (Notice that closing the connection doesn't terminate the processing loop,
119
- # or change the fact that your echo server is still accepting connections!)
65
+ # * {EventMachine.defer}
66
+ # * {EventMachine.next_tick}
120
67
  #
121
- # == Questions and Futures
122
- # Would it be useful for EventMachine to incorporate the Observer pattern
123
- # and make use of the corresponding Ruby <tt>observer</tt> package?
124
- # Interesting thought.
68
+ # ### Efficient proxying ###
125
69
  #
70
+ # * {EventMachine.enable_proxy}
71
+ # * {EventMachine.disable_proxy}
126
72
  module EventMachine
127
73
  class << self
128
74
  # Exposed to allow joining on the thread, when run in a multithreaded
129
75
  # environment. Performing other actions on the thread has undefined
130
- # semantics.
76
+ # semantics (read: a dangerous endevor).
77
+ #
78
+ # @return [Thread]
131
79
  attr_reader :reactor_thread
132
80
  end
133
81
  @next_tick_mutex = Mutex.new
134
82
  @reactor_running = false
135
83
  @next_tick_queue = []
84
+ @tails = []
136
85
  @threadpool = nil
137
-
138
-
139
- # EventMachine::run initializes and runs an event loop.
140
- # This method only returns if user-callback code calls stop_event_loop.
141
- # Use the supplied block to define your clients and servers.
142
- # The block is called by EventMachine::run immediately after initializing
143
- # its internal event loop but <i>before</i> running the loop.
144
- # Therefore this block is the right place to call start_server if you
145
- # want to accept connections from remote clients.
146
- #
147
- # For programs that are structured as servers, it's usually appropriate
148
- # to start an event loop by calling EventMachine::run, and let it
149
- # run forever. It's also possible to use EventMachine::run to make a single
150
- # client-connection to a remote server, process the data flow from that
151
- # single connection, and then call stop_event_loop to force EventMachine::run
152
- # to return. Your program will then continue from the point immediately
153
- # following the call to EventMachine::run.
154
- #
155
- # You can of course do both client and servers simultaneously in the same program.
156
- # One of the strengths of the event-driven programming model is that the
157
- # handling of network events on many different connections will be interleaved,
158
- # and scheduled according to the actual events themselves. This maximizes
159
- # efficiency.
160
- #
161
- # === Server usage example
162
- #
163
- # See EventMachine.start_server
164
- #
165
- # === Client usage example
166
- #
167
- # See EventMachine.connect
168
- #
169
- #--
170
- # Obsoleted the use_threads mechanism.
171
- # 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
172
- # gets called even if an exception gets thrown within any of the user code
173
- # that the event loop runs. The best way to see this is to run a unit
174
- # test with two functions, each of which calls EventMachine#run and each of
175
- # which throws something inside of #run. Without the ensure, the second test
176
- # will start without release_machine being called and will immediately throw
177
- # a C++ runtime error.
86
+
87
+ # System errnos
88
+ # @private
89
+ ERRNOS = Errno::constants.grep(/^E/).inject(Hash.new(:unknown)) { |hash, name|
90
+ errno = Errno.__send__(:const_get, name)
91
+ hash[errno::Errno] = errno
92
+ hash
93
+ }
94
+
95
+ # Initializes and runs an event loop. This method only returns if code inside the block passed to this method
96
+ # calls {EventMachine.stop_event_loop}. The block is executed after initializing its internal event loop but *before* running the loop,
97
+ # therefore this block is the right place to call any code that needs event loop to run, for example, {EventMachine.start_server},
98
+ # {EventMachine.connect} or similar methods of libraries that use EventMachine under the hood
99
+ # (like `EventMachine::HttpRequest.new` or `AMQP.start`).
100
+ #
101
+ # Programs that are run for long periods of time (e.g. servers) usually start event loop by calling {EventMachine.run}, and let it
102
+ # run "forever". It's also possible to use {EventMachine.run} to make a single client-connection to a remote server,
103
+ # process the data flow from that single connection, and then call {EventMachine.stop_event_loop} to stop, in other words,
104
+ # to run event loop for a short period of time (necessary to complete some operation) and then shut it down.
105
+ #
106
+ # Once event loop is running, it is perfectly possible to start multiple servers and clients simultaneously: content-aware
107
+ # proxies like [Proxymachine](https://github.com/mojombo/proxymachine) do just that.
108
+ #
109
+ # ## Using EventMachine with Ruby on Rails and other Web application frameworks ##
110
+ #
111
+ # Standalone applications often run event loop on the main thread, thus blocking for their entire lifespan. In case of Web applications,
112
+ # if you are running an EventMachine-based app server such as [Thin](http://code.macournoyer.com/thin/) or [Goliath](https://github.com/postrank-labs/goliath/),
113
+ # they start event loop for you. Servers like Unicorn, Apache Passenger or Mongrel occupy main Ruby thread to serve HTTP(S) requests. This means
114
+ # that calling {EventMachine.run} on the same thread is not an option (it will result in Web server never binding to the socket).
115
+ # In that case, start event loop in a separate thread as demonstrated below.
116
+ #
117
+ #
118
+ # @example Starting EventMachine event loop in the current thread to run the "Hello, world"-like Echo server example
119
+ #
120
+ # #!/usr/bin/env ruby
121
+ #
122
+ # require 'rubygems' # or use Bundler.setup
123
+ # require 'eventmachine'
124
+ #
125
+ # class EchoServer < EM::Connection
126
+ # def receive_data(data)
127
+ # send_data(data)
128
+ # end
129
+ # end
130
+ #
131
+ # EventMachine.run do
132
+ # EventMachine.start_server("0.0.0.0", 10000, EchoServer)
133
+ # end
134
+ #
178
135
  #
136
+ # @example Starting EventMachine event loop in a separate thread
137
+ #
138
+ # # doesn't block current thread, can be used with Ruby on Rails, Sinatra, Merb, Rack
139
+ # # and any other application server that occupies main Ruby thread.
140
+ # Thread.new { EventMachine.run }
141
+ #
142
+ #
143
+ # @note This method blocks calling thread. If you need to start EventMachine event loop from a Web app
144
+ # running on a non event-driven server (Unicorn, Apache Passenger, Mongrel), do it in a separate thread like demonstrated
145
+ # in one of the examples.
146
+ # @see file:docs/GettingStarted.md Getting started with EventMachine
147
+ # @see EventMachine.stop_event_loop
179
148
  def self.run blk=nil, tail=nil, &block
180
- @tails ||= []
149
+ # Obsoleted the use_threads mechanism.
150
+ # 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
151
+ # gets called even if an exception gets thrown within any of the user code
152
+ # that the event loop runs. The best way to see this is to run a unit
153
+ # test with two functions, each of which calls {EventMachine.run} and each of
154
+ # which throws something inside of #run. Without the ensure, the second test
155
+ # will start without release_machine being called and will immediately throw
156
+
157
+ #
158
+
159
+
181
160
  tail and @tails.unshift(tail)
182
161
 
183
162
  if reactor_running?
@@ -188,6 +167,7 @@ module EventMachine
188
167
  @timers = {}
189
168
  @wrapped_exception = nil
190
169
  @next_tick_queue ||= []
170
+ @tails ||= []
191
171
  begin
192
172
  @reactor_running = true
193
173
  initialize_event_machine
@@ -235,8 +215,8 @@ module EventMachine
235
215
 
236
216
  # Sugars a common use case. Will pass the given block to #run, but will terminate
237
217
  # the reactor loop and exit the function as soon as the code in the block completes.
238
- # (Normally, #run keeps running indefinitely, even after the block supplied to it
239
- # finishes running, until user code calls #stop.)
218
+ # (Normally, {EventMachine.run} keeps running indefinitely, even after the block supplied to it
219
+ # finishes running, until user code calls {EventMachine.stop})
240
220
  #
241
221
  def self.run_block &block
242
222
  pr = proc {
@@ -246,13 +226,13 @@ module EventMachine
246
226
  run(&pr)
247
227
  end
248
228
 
249
- # Returns true if the calling thread is the same thread as the reactor.
229
+ # @return [Boolean] true if the calling thread is the same thread as the reactor.
250
230
  def self.reactor_thread?
251
231
  Thread.current == @reactor_thread
252
232
  end
253
233
 
254
234
  # Runs the given callback on the reactor thread, or immediately if called
255
- # from the reactor thread. Accepts the same arguments as EM::Callback
235
+ # from the reactor thread. Accepts the same arguments as {EventMachine::Callback}
256
236
  def self.schedule(*a, &b)
257
237
  cb = Callback(*a, &b)
258
238
  if reactor_running? && reactor_thread?
@@ -262,13 +242,12 @@ module EventMachine
262
242
  end
263
243
  end
264
244
 
265
- # fork_reactor forks a new process and calls EM#run inside of it, passing your block.
266
- #--
267
- # This implementation is subject to change, especially if we clean up the relationship
268
- # of EM#run to @reactor_running.
269
- # Original patch by Aman Gupta.
270
- #
245
+ # Forks a new process, properly stops the reactor and then calls {EventMachine.run} inside of it again, passing your block.
271
246
  def self.fork_reactor &block
247
+ # This implementation is subject to change, especially if we clean up the relationship
248
+ # of EM#run to @reactor_running.
249
+ # Original patch by Aman Gupta.
250
+ #
272
251
  Kernel.fork do
273
252
  if self.reactor_running?
274
253
  self.stop_event_loop
@@ -279,43 +258,54 @@ module EventMachine
279
258
  end
280
259
  end
281
260
 
282
- # EventMachine#add_timer adds a one-shot timer to the event loop.
261
+ # Adds a block to call as the reactor is shutting down.
262
+ #
263
+ # These callbacks are called in the _reverse_ order to which they are added.
264
+ #
265
+ # @example Scheduling operations to be run when EventMachine event loop is stopped
266
+ #
267
+ # EventMachine.run do
268
+ # EventMachine.add_shutdown_hook { puts "b" }
269
+ # EventMachine.add_shutdown_hook { puts "a" }
270
+ # EventMachine.stop
271
+ # end
272
+ #
273
+ # # Outputs:
274
+ # # a
275
+ # # b
276
+ #
277
+ def self.add_shutdown_hook &block
278
+ @tails << block
279
+ end
280
+
281
+ # Adds a one-shot timer to the event loop.
283
282
  # Call it with one or two parameters. The first parameters is a delay-time
284
- # expressed in <i>seconds</i> (not milliseconds). The second parameter, if
285
- # present, must be a proc object. If a proc object is not given, then you
283
+ # expressed in *seconds* (not milliseconds). The second parameter, if
284
+ # present, must be an object that responds to :call. If 2nd parameter is not given, then you
286
285
  # can also simply pass a block to the method call.
287
286
  #
288
- # EventMachine#add_timer may be called from the block passed to EventMachine#run
287
+ # This method may be called from the block passed to {EventMachine.run}
289
288
  # or from any callback method. It schedules execution of the proc or block
290
- # passed to add_timer, after the passage of an interval of time equal to
291
- # <i>at least</i> the number of seconds specified in the first parameter to
289
+ # passed to it, after the passage of an interval of time equal to
290
+ # *at least* the number of seconds specified in the first parameter to
292
291
  # the call.
293
292
  #
294
- # EventMachine#add_timer is a <i>non-blocking</i> call. Callbacks can and will
293
+ # {EventMachine.add_timer} is a non-blocking method. Callbacks can and will
295
294
  # be called during the interval of time that the timer is in effect.
296
295
  # There is no built-in limit to the number of timers that can be outstanding at
297
296
  # any given time.
298
297
  #
299
- # === Usage example
300
- #
301
- # This example shows how easy timers are to use. Observe that two timers are
302
- # initiated simultaneously. Also, notice that the event loop will continue
303
- # to run even after the second timer event is processed, since there was
304
- # no call to EventMachine#stop_event_loop. There will be no activity, of
305
- # course, since no network clients or servers are defined. Stop the program
306
- # with Ctrl-C.
298
+ # @example Setting a one-shot timer with EventMachine
307
299
  #
308
- # EventMachine::run {
300
+ # EventMachine.run {
309
301
  # puts "Starting the run now: #{Time.now}"
310
- # EventMachine::add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
311
- # EventMachine::add_timer( 10 ) { puts "Executing timer event: #{Time.now}" }
302
+ # EventMachine.add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
303
+ # EventMachine.add_timer(10) { puts "Executing timer event: #{Time.now}" }
312
304
  # }
313
305
  #
314
- #
315
- # Also see EventMachine::Timer
316
- #--
317
- # Changed 04Oct06: We now pass the interval as an integer number of milliseconds.
318
- #
306
+ # @param [Integer] delay Delay in seconds
307
+ # @see EventMachine::Timer
308
+ # @see EventMachine.add_periodic_timer
319
309
  def self.add_timer *args, &block
320
310
  interval = args.shift
321
311
  code = args.shift || block
@@ -327,24 +317,22 @@ module EventMachine
327
317
  end
328
318
  end
329
319
 
330
- # EventMachine#add_periodic_timer adds a periodic timer to the event loop.
331
- # It takes the same parameters as the one-shot timer method, EventMachine#add_timer.
320
+ # Adds a periodic timer to the event loop.
321
+ # It takes the same parameters as the one-shot timer method, {EventMachine.add_timer}.
332
322
  # This method schedules execution of the given block repeatedly, at intervals
333
- # of time <i>at least</i> as great as the number of seconds given in the first
323
+ # of time *at least* as great as the number of seconds given in the first
334
324
  # parameter to the call.
335
- #
336
- # === Usage example
337
325
  #
338
- # The following sample program will write a dollar-sign to stderr every five seconds.
339
- # (Of course if the program defined network clients and/or servers, they would
340
- # be doing their work while the periodic timer is counting off.)
326
+ # @example Write a dollar-sign to stderr every five seconds, without blocking
341
327
  #
342
- # EventMachine::run {
343
- # EventMachine::add_periodic_timer( 5 ) { $stderr.write "$" }
328
+ # EventMachine.run {
329
+ # EventMachine.add_periodic_timer( 5 ) { $stderr.write "$" }
344
330
  # }
345
331
  #
332
+ # @param [Integer] delay Delay in seconds
346
333
  #
347
- # Also see EventMachine::PeriodicTimer
334
+ # @see EventMachine::PeriodicTimer
335
+ # @see EventMachine.add_timer
348
336
  #
349
337
  def self.add_periodic_timer *args, &block
350
338
  interval = args.shift
@@ -353,8 +341,11 @@ module EventMachine
353
341
  EventMachine::PeriodicTimer.new(interval, code)
354
342
  end
355
343
 
356
- # Cancel a timer using its signature. You can also use EventMachine::Timer#cancel
344
+
345
+ # Cancel a timer (can be a callback or an {EventMachine::Timer} instance).
357
346
  #
347
+ # @param [#cancel, #call] timer_or_sig A timer to cancel
348
+ # @see EventMachine::Timer#cancel
358
349
  def self.cancel_timer timer_or_sig
359
350
  if timer_or_sig.respond_to? :cancel
360
351
  timer_or_sig.cancel
@@ -364,19 +355,14 @@ module EventMachine
364
355
  end
365
356
 
366
357
 
367
- # stop_event_loop may called from within a callback method
368
- # while EventMachine's processing loop is running.
369
- # It causes the processing loop to stop executing, which
370
- # will cause all open connections and accepting servers
371
- # to be run down and closed. <i>Callbacks for connection-termination
372
- # will be called</i> as part of the processing of stop_event_loop.
373
- # (There currently is no option to panic-stop the loop without
374
- # closing connections.) When all of this processing is complete,
375
- # the call to EventMachine::run which started the processing loop
376
- # will return and program flow will resume from the statement
377
- # following EventMachine::run call.
358
+ # Causes the processing loop to stop executing, which will cause all open connections and accepting servers
359
+ # to be run down and closed. Connection termination callbacks added using {EventMachine.add_shutdown_hook}
360
+ # will be called as part of running this method.
361
+ #
362
+ # When all of this processing is complete, the call to {EventMachine.run} which started the processing loop
363
+ # will return and program flow will resume from the statement following {EventMachine.run} call.
378
364
  #
379
- # === Usage example
365
+ # @example Stopping a running EventMachine event loop
380
366
  #
381
367
  # require 'rubygems'
382
368
  # require 'eventmachine'
@@ -386,40 +372,40 @@ module EventMachine
386
372
  # puts "We're sending a dumb HTTP request to the remote peer."
387
373
  # send_data "GET / HTTP/1.1\r\nHost: www.microsoft.com\r\n\r\n"
388
374
  # end
389
- #
375
+ #
390
376
  # def receive_data data
391
377
  # puts "We received #{data.length} bytes from the remote peer."
392
378
  # puts "We're going to stop the event loop now."
393
379
  # EventMachine::stop_event_loop
394
380
  # end
395
- #
381
+ #
396
382
  # def unbind
397
383
  # puts "A connection has terminated."
398
384
  # end
399
385
  # end
400
- #
386
+ #
401
387
  # puts "We're starting the event loop now."
402
- # EventMachine::run {
403
- # EventMachine::connect "www.microsoft.com", 80, Redmond
388
+ # EventMachine.run {
389
+ # EventMachine.connect "www.microsoft.com", 80, Redmond
404
390
  # }
405
391
  # puts "The event loop has stopped."
406
- #
407
- # This program will produce approximately the following output:
408
392
  #
409
- # We're starting the event loop now.
410
- # We're sending a dumb HTTP request to the remote peer.
411
- # We received 1440 bytes from the remote peer.
412
- # We're going to stop the event loop now.
413
- # A connection has terminated.
414
- # The event loop has stopped.
393
+ # # This program will produce approximately the following output:
394
+ # #
395
+ # # We're starting the event loop now.
396
+ # # We're sending a dumb HTTP request to the remote peer.
397
+ # # We received 1440 bytes from the remote peer.
398
+ # # We're going to stop the event loop now.
399
+ # # A connection has terminated.
400
+ # # The event loop has stopped.
415
401
  #
416
402
  #
417
403
  def self.stop_event_loop
418
404
  EventMachine::stop
419
405
  end
420
406
 
421
- # EventMachine::start_server initiates a TCP server (socket
422
- # acceptor) on the specified IP address and port.
407
+ # Initiates a TCP server (socket acceptor) on the specified IP address and port.
408
+ #
423
409
  # The IP address must be valid on the machine where the program
424
410
  # runs, and the process must be privileged enough to listen
425
411
  # on the specified port (on Unix-like systems, superuser privileges
@@ -427,35 +413,37 @@ module EventMachine
427
413
  # Only one listener may be running on any given address/port
428
414
  # combination. start_server will fail if the given address and port
429
415
  # are already listening on the machine, either because of a prior call
430
- # to start_server or some unrelated process running on the machine.
431
- # If start_server succeeds, the new network listener becomes active
416
+ # to {.start_server} or some unrelated process running on the machine.
417
+ # If {.start_server} succeeds, the new network listener becomes active
432
418
  # immediately and starts accepting connections from remote peers,
433
419
  # and these connections generate callback events that are processed
434
- # by the code specified in the handler parameter to start_server.
420
+ # by the code specified in the handler parameter to {.start_server}.
435
421
  #
436
- # The optional handler which is passed to start_server is the key
422
+ # The optional handler which is passed to this method is the key
437
423
  # to EventMachine's ability to handle particular network protocols.
438
424
  # The handler parameter passed to start_server must be a Ruby Module
439
425
  # that you must define. When the network server that is started by
440
426
  # start_server accepts a new connection, it instantiates a new
441
- # object of an anonymous class that is inherited from EventMachine::Connection,
442
- # <i>into which the methods from your handler have been mixed.</i>
443
- # Your handler module may redefine any of the methods in EventMachine::Connection
444
- # in order to implement the specific behavior of the network protocol.
427
+ # object of an anonymous class that is inherited from {EventMachine::Connection},
428
+ # *into which your handler module have been included*.
445
429
  #
446
- # Callbacks invoked in response to network events <i>always</i> take place
447
- # within the execution context of the object derived from EventMachine::Connection
430
+ # Your handler module may override any of the methods in {EventMachine::Connection},
431
+ # such as {EventMachine::Connection#receive_data}, in order to implement the specific behavior
432
+ # of the network protocol.
433
+ #
434
+ # Callbacks invoked in response to network events *always* take place
435
+ # within the execution context of the object derived from {EventMachine::Connection}
448
436
  # extended by your handler module. There is one object per connection, and
449
437
  # all of the callbacks invoked for a particular connection take the form
450
- # of instance methods called against the corresponding EventMachine::Connection
438
+ # of instance methods called against the corresponding {EventMachine::Connection}
451
439
  # object. Therefore, you are free to define whatever instance variables you
452
440
  # wish, in order to contain the per-connection state required by the network protocol you are
453
441
  # implementing.
454
442
  #
455
- # start_server is often called inside the block passed to EventMachine::run,
456
- # but it can be called from any EventMachine callback. start_server will fail
443
+ # {EventMachine.start_server} is usually called inside the block passed to {EventMachine.run},
444
+ # but it can be called from any EventMachine callback. {EventMachine.start_server} will fail
457
445
  # unless the EventMachine event loop is currently running (which is why
458
- # it's often called in the block suppled to EventMachine::run).
446
+ # it's often called in the block suppled to {EventMachine.run}).
459
447
  #
460
448
  # You may call start_server any number of times to start up network
461
449
  # listeners on different address/port combinations. The servers will
@@ -463,29 +451,29 @@ module EventMachine
463
451
  # can specify a different handler module and thus implement a different
464
452
  # network protocol from all the others.
465
453
  #
466
- # === Usage example
467
- # Here is an example of a server that counts lines of input from the remote
468
- # peer and sends back the total number of lines received, after each line.
469
- # Try the example with more than one client connection opened via telnet,
470
- # and you will see that the line count increments independently on each
471
- # of the client connections. Also very important to note, is that the
472
- # handler for the receive_data function, which our handler redefines, may
473
- # not assume that the data it receives observes any kind of message boundaries.
474
- # Also, to use this example, be sure to change the server and port parameters
475
- # to the start_server call to values appropriate for your environment.
454
+ # @example
476
455
  #
477
456
  # require 'rubygems'
478
457
  # require 'eventmachine'
479
458
  #
459
+ # # Here is an example of a server that counts lines of input from the remote
460
+ # # peer and sends back the total number of lines received, after each line.
461
+ # # Try the example with more than one client connection opened via telnet,
462
+ # # and you will see that the line count increments independently on each
463
+ # # of the client connections. Also very important to note, is that the
464
+ # # handler for the receive_data function, which our handler redefines, may
465
+ # # not assume that the data it receives observes any kind of message boundaries.
466
+ # # Also, to use this example, be sure to change the server and port parameters
467
+ # # to the start_server call to values appropriate for your environment.
480
468
  # module LineCounter
481
469
  # MaxLinesPerConnection = 10
482
- #
470
+ #
483
471
  # def post_init
484
472
  # puts "Received a new connection"
485
473
  # @data_received = ""
486
474
  # @line_count = 0
487
475
  # end
488
- #
476
+ #
489
477
  # def receive_data data
490
478
  # @data_received << data
491
479
  # while @data_received.slice!( /^[^\n]*[\n]/m )
@@ -495,15 +483,22 @@ module EventMachine
495
483
  # end
496
484
  # end
497
485
  # end
498
- #
499
- # EventMachine::run {
500
- # host,port = "192.168.0.100", 8090
501
- # EventMachine::start_server host, port, LineCounter
486
+ #
487
+ # EventMachine.run {
488
+ # host, port = "192.168.0.100", 8090
489
+ # EventMachine.start_server host, port, LineCounter
502
490
  # puts "Now accepting connections on address #{host}, port #{port}..."
503
- # EventMachine::add_periodic_timer( 10 ) { $stderr.write "*" }
491
+ # EventMachine.add_periodic_timer(10) { $stderr.write "*" }
504
492
  # }
505
- #
506
493
  #
494
+ # @param [String] server Host to bind to.
495
+ # @param [Integer] port Port to bind to.
496
+ # @param [Module, Class] handler A module or class that implements connection callbacks
497
+ #
498
+ # @note Don't forget that in order to bind to ports < 1024 on Linux, *BSD and Mac OS X your process must have superuser privileges.
499
+ #
500
+ # @see file:docs/GettingStarted.md EventMachine tutorial
501
+ # @see EventMachine.stop_server
507
502
  def self.start_server server, port=nil, handler=nil, *args, &block
508
503
  begin
509
504
  port = Integer(port)
@@ -527,122 +522,118 @@ module EventMachine
527
522
  end
528
523
 
529
524
 
530
- # Stop a TCP server socket that was started with EventMachine#start_server.
531
- #--
532
- # Requested by Kirk Haines. TODO, this isn't OOP enough. We ought somehow
533
- # to have #start_server return an object that has a close or a stop method on it.
534
- #
525
+ # Stop a TCP server socket that was started with {EventMachine.start_server}.
526
+ # @see EventMachine.start_server
535
527
  def self.stop_server signature
536
528
  EventMachine::stop_tcp_server signature
537
529
  end
538
530
 
539
- # Start a Unix-domain server
531
+ # Start a Unix-domain server.
532
+ #
533
+ # Note that this is an alias for {EventMachine.start_server}, which can be used to start both
534
+ # TCP and Unix-domain servers.
540
535
  #
541
- # Note that this is an alias for EventMachine::start_server, which can be used to start both
542
- # TCP and Unix-domain servers
536
+ # @see EventMachine.start_server
543
537
  def self.start_unix_domain_server filename, *args, &block
544
538
  start_server filename, *args, &block
545
539
  end
546
540
 
547
- # EventMachine#connect initiates a TCP connection to a remote
548
- # server and sets up event-handling for the connection.
549
- # You can call EventMachine#connect in the block supplied
550
- # to EventMachine#run or in any callback method.
541
+ # Initiates a TCP connection to a remote server and sets up event handling for the connection.
542
+ # {EventMachine.connect} requires event loop to be running (see {EventMachine.run}).
551
543
  #
552
- # EventMachine#connect takes the IP address (or hostname) and
544
+ # {EventMachine.connect} takes the IP address (or hostname) and
553
545
  # port of the remote server you want to connect to.
554
- # It also takes an optional handler Module which you must define, that
555
- # contains the callbacks that will be invoked by the event loop
556
- # on behalf of the connection.
546
+ # It also takes an optional handler (a module or a subclass of {EventMachine::Connection}) which you must define, that
547
+ # contains the callbacks that will be invoked by the event loop on behalf of the connection.
557
548
  #
558
- # See the description of EventMachine#start_server for a discussion
559
- # of the handler Module. All of the details given in that description
560
- # apply for connections created with EventMachine#connect.
549
+ # Learn more about connection lifecycle callbacks in the {file:docs/GettingStarted.md EventMachine tutorial} and
550
+ # {file:docs/ConnectionLifecycleCallbacks.md Connection lifecycle guide}.
561
551
  #
562
- # === Usage Example
563
552
  #
564
- # Here's a program which connects to a web server, sends a naive
565
- # request, parses the HTTP header of the response, and then
566
- # (antisocially) ends the event loop, which automatically drops the connection
567
- # (and incidentally calls the connection's unbind method).
568
- #
553
+ # @example
554
+ #
555
+ # # Here's a program which connects to a web server, sends a naive
556
+ # # request, parses the HTTP header of the response, and then
557
+ # # (antisocially) ends the event loop, which automatically drops the connection
558
+ # # (and incidentally calls the connection's unbind method).
569
559
  # module DumbHttpClient
570
560
  # def post_init
571
561
  # send_data "GET / HTTP/1.1\r\nHost: _\r\n\r\n"
572
562
  # @data = ""
573
563
  # @parsed = false
574
564
  # end
575
- #
565
+ #
576
566
  # def receive_data data
577
567
  # @data << data
578
568
  # if !@parsed and @data =~ /[\n][\r]*[\n]/m
579
569
  # @parsed = true
580
570
  # puts "RECEIVED HTTP HEADER:"
581
571
  # $`.each {|line| puts ">>> #{line}" }
582
- #
572
+ #
583
573
  # puts "Now we'll terminate the loop, which will also close the connection"
584
574
  # EventMachine::stop_event_loop
585
575
  # end
586
576
  # end
587
- #
577
+ #
588
578
  # def unbind
589
579
  # puts "A connection has terminated"
590
580
  # end
591
581
  # end
592
- #
593
- # EventMachine::run {
594
- # EventMachine::connect "www.bayshorenetworks.com", 80, DumbHttpClient
582
+ #
583
+ # EventMachine.run {
584
+ # EventMachine.connect "www.bayshorenetworks.com", 80, DumbHttpClient
595
585
  # }
596
586
  # puts "The event loop has ended"
597
- #
598
587
  #
599
- # There are times when it's more convenient to define a protocol handler
600
- # as a Class rather than a Module. Here's how to do this:
588
+ #
589
+ # @example Defining protocol handler as a class
601
590
  #
602
591
  # class MyProtocolHandler < EventMachine::Connection
603
592
  # def initialize *args
604
593
  # super
605
594
  # # whatever else you want to do here
606
595
  # end
607
- #
608
- # #.......your other class code
596
+ #
597
+ # # ...
609
598
  # end
610
599
  #
611
- # If you do this, then an instance of your class will be instantiated to handle
612
- # every network connection created by your code or accepted by servers that you
613
- # create. If you redefine #post_init in your protocol-handler class, your
614
- # #post_init method will be called _inside_ the call to #super that you will
615
- # make in your #initialize method (if you provide one).
616
- #
617
- #--
618
- # EventMachine::connect initiates a TCP connection to a remote
619
- # server and sets up event-handling for the connection.
620
- # It internally creates an object that should not be handled
621
- # by the caller. HOWEVER, it's often convenient to get the
622
- # object to set up interfacing to other objects in the system.
623
- # We return the newly-created anonymous-class object to the caller.
624
- # It's expected that a considerable amount of code will depend
625
- # on this behavior, so don't change it.
626
- #
627
- # Ok, added support for a user-defined block, 13Apr06.
628
- # This leads us to an interesting choice because of the
629
- # presence of the post_init call, which happens in the
630
- # initialize method of the new object. We call the user's
631
- # block and pass the new object to it. This is a great
632
- # way to do protocol-specific initiation. It happens
633
- # AFTER post_init has been called on the object, which I
634
- # certainly hope is the right choice.
635
- # Don't change this lightly, because accepted connections
636
- # are different from connected ones and we don't want
637
- # to have them behave differently with respect to post_init
638
- # if at all possible.
639
600
  #
601
+ # @param [String] server Host to connect to
602
+ # @param [Integer] port Port to connect to
603
+ # @param [Module, Class] handler A module or class that implements connection lifecycle callbacks
604
+ #
605
+ # @see EventMachine.start_server
606
+ # @see file:docs/GettingStarted.md EventMachine tutorial
640
607
  def self.connect server, port=nil, handler=nil, *args, &blk
608
+ # EventMachine::connect initiates a TCP connection to a remote
609
+ # server and sets up event-handling for the connection.
610
+ # It internally creates an object that should not be handled
611
+ # by the caller. HOWEVER, it's often convenient to get the
612
+ # object to set up interfacing to other objects in the system.
613
+ # We return the newly-created anonymous-class object to the caller.
614
+ # It's expected that a considerable amount of code will depend
615
+ # on this behavior, so don't change it.
616
+ #
617
+ # Ok, added support for a user-defined block, 13Apr06.
618
+ # This leads us to an interesting choice because of the
619
+ # presence of the post_init call, which happens in the
620
+ # initialize method of the new object. We call the user's
621
+ # block and pass the new object to it. This is a great
622
+ # way to do protocol-specific initiation. It happens
623
+ # AFTER post_init has been called on the object, which I
624
+ # certainly hope is the right choice.
625
+ # Don't change this lightly, because accepted connections
626
+ # are different from connected ones and we don't want
627
+ # to have them behave differently with respect to post_init
628
+ # if at all possible.
629
+
641
630
  bind_connect nil, nil, server, port, handler, *args, &blk
642
631
  end
643
632
 
644
- # EventMachine::bind_connect is like EventMachine::connect, but allows for a local address/port
633
+ # This method is like {EventMachine.connect}, but allows for a local address/port
645
634
  # to bind the connection to.
635
+ #
636
+ # @see EventMachine.connect
646
637
  def self.bind_connect bind_addr, bind_port, server, port=nil, handler=nil, *args
647
638
  begin
648
639
  port = Integer(port)
@@ -672,18 +663,18 @@ module EventMachine
672
663
  c
673
664
  end
674
665
 
675
- # EventMachine::watch registers a given file descriptor or IO object with the eventloop. The
666
+ # {EventMachine.watch} registers a given file descriptor or IO object with the eventloop. The
676
667
  # file descriptor will not be modified (it will remain blocking or non-blocking).
677
668
  #
678
669
  # The eventloop can be used to process readable and writable events on the file descriptor, using
679
- # EventMachine::Connection#notify_readable= and EventMachine::Connection#notify_writable=
670
+ # {EventMachine::Connection#notify_readable=} and {EventMachine::Connection#notify_writable=}
680
671
  #
681
- # EventMachine::Connection#notify_readable? and EventMachine::Connection#notify_writable? can be used
672
+ # {EventMachine::Connection#notify_readable?} and {EventMachine::Connection#notify_writable?} can be used
682
673
  # to check what events are enabled on the connection.
683
674
  #
684
- # To detach the file descriptor, use EventMachine::Connection#detach
675
+ # To detach the file descriptor, use {EventMachine::Connection#detach}
685
676
  #
686
- # === Usage Example
677
+ # @example
687
678
  #
688
679
  # module SimpleHttpClient
689
680
  # def notify_readable
@@ -705,15 +696,14 @@ module EventMachine
705
696
  # end
706
697
  # end
707
698
  #
708
- # EM.run{
709
- # $sock = TCPSocket.new('site.com', 80)
710
- # $sock.write("GET / HTTP/1.0\r\n\r\n")
711
- # conn = EM.watch $sock, SimpleHttpClient
699
+ # EventMachine.run {
700
+ # sock = TCPSocket.new('site.com', 80)
701
+ # sock.write("GET / HTTP/1.0\r\n\r\n")
702
+ # conn = EventMachine.watch(sock, SimpleHttpClient)
712
703
  # conn.notify_readable = true
713
704
  # }
714
705
  #
715
- #--
716
- # Thanks to Riham Aldakkak (eSpace Technologies) for the initial patch
706
+ # @author Riham Aldakkak (eSpace Technologies)
717
707
  def EventMachine::watch io, handler=nil, *args, &blk
718
708
  attach_io io, true, handler, *args, &blk
719
709
  end
@@ -722,13 +712,14 @@ module EventMachine
722
712
  # The file descriptor will be set as non-blocking, and EventMachine will process
723
713
  # receive_data and send_data events on it as it would for any other connection.
724
714
  #
725
- # To watch a fd instead, use EventMachine::watch, which will not alter the state of the socket
715
+ # To watch a fd instead, use {EventMachine.watch}, which will not alter the state of the socket
726
716
  # and fire notify_readable and notify_writable events instead.
727
717
  def EventMachine::attach io, handler=nil, *args, &blk
728
718
  attach_io io, false, handler, *args, &blk
729
719
  end
730
720
 
731
- def EventMachine::attach_io io, watch_mode, handler=nil, *args # :nodoc:
721
+ # @private
722
+ def EventMachine::attach_io io, watch_mode, handler=nil, *args
732
723
  klass = klass_from_handler(Connection, handler, *args)
733
724
 
734
725
  if !watch_mode and klass.public_instance_methods.any?{|m| [:notify_readable, :notify_writable].include? m.to_sym }
@@ -753,17 +744,19 @@ module EventMachine
753
744
  end
754
745
 
755
746
 
756
- # Connect to a given host/port and re-use the provided EventMachine::Connection instance
757
- #--
758
- # Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
759
- # because we haven't set up the connection in @conns by that point.
760
- # RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
761
- #
762
- # Changed 22Nov06: if called on an already-connected handler, just return the
763
- # handler and do nothing more. Originally this condition raised an exception.
764
- # We may want to change it yet again and call the block, if any.
747
+ # Connect to a given host/port and re-use the provided {EventMachine::Connection} instance.
748
+ # Consider also {EventMachine::Connection#reconnect}.
765
749
  #
766
- def self.reconnect server, port, handler # :nodoc:
750
+ # @see EventMachine::Connection#reconnect
751
+ def self.reconnect server, port, handler
752
+ # Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
753
+ # because we haven't set up the connection in @conns by that point.
754
+ # RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
755
+ #
756
+ # Changed 22Nov06: if called on an already-connected handler, just return the
757
+ # handler and do nothing more. Originally this condition raised an exception.
758
+ # We may want to change it yet again and call the block, if any.
759
+
767
760
  raise "invalid handler" unless handler.respond_to?(:connection_completed)
768
761
  #raise "still connected" if @conns.has_key?(handler.signature)
769
762
  return handler if @conns.has_key?(handler.signature)
@@ -776,90 +769,77 @@ module EventMachine
776
769
  end
777
770
 
778
771
 
779
- # Make a connection to a Unix-domain socket. This is not implemented on Windows platforms.
780
- # The parameter socketname is a String which identifies the Unix-domain socket you want
781
- # to connect to. socketname is the name of a file on your local system, and in most cases
782
- # is a fully-qualified path name. Make sure that your process has enough local permissions
783
- # to open the Unix-domain socket.
784
- # See also the documentation for #connect. This method behaves like #connect
785
- # in all respects except for the fact that it connects to a local Unix-domain
786
- # socket rather than a TCP socket.
787
- #
788
- # Note that this method is simply an alias for #connect, which can connect to both TCP
789
- # and Unix-domain sockets
790
- #--
791
- # For making connections to Unix-domain sockets.
792
- # Eventually this has to get properly documented and unified with the TCP-connect methods.
793
- # Note how nearly identical this is to EventMachine#connect
772
+ # Make a connection to a Unix-domain socket. This method is simply an alias for {.connect},
773
+ # which can connect to both TCP and Unix-domain sockets. Make sure that your process has sufficient
774
+ # permissions to open the socket it is given.
775
+ #
776
+ # @param [String] socketname Unix domain socket (local fully-qualified path) you want to connect to.
777
+ #
778
+ # @note UNIX sockets, as the name suggests, are not available on Microsoft Windows.
794
779
  def self.connect_unix_domain socketname, *args, &blk
795
780
  connect socketname, *args, &blk
796
781
  end
797
782
 
798
783
 
799
- # EventMachine#open_datagram_socket is for support of UDP-based
800
- # protocols. Its usage is similar to that of EventMachine#start_server.
801
- # It takes three parameters: an IP address (which must be valid
802
- # on the machine which executes the method), a port number,
803
- # and an optional Module name which will handle the data.
784
+ # Used for UDP-based protocols. Its usage is similar to that of {EventMachine.start_server}.
785
+ #
804
786
  # This method will create a new UDP (datagram) socket and
805
787
  # bind it to the address and port that you specify.
806
- # The normal callbacks (see EventMachine#start_server) will
788
+ # The normal callbacks (see {EventMachine.start_server}) will
807
789
  # be called as events of interest occur on the newly-created
808
790
  # socket, but there are some differences in how they behave.
809
791
  #
810
- # Connection#receive_data will be called when a datagram packet
792
+ # {Connection#receive_data} will be called when a datagram packet
811
793
  # is received on the socket, but unlike TCP sockets, the message
812
794
  # boundaries of the received data will be respected. In other words,
813
795
  # if the remote peer sent you a datagram of a particular size,
814
- # you may rely on Connection#receive_data to give you the
796
+ # you may rely on {Connection#receive_data} to give you the
815
797
  # exact data in the packet, with the original data length.
816
798
  # Also observe that Connection#receive_data may be called with a
817
- # <i>zero-length</i> data payload, since empty datagrams are permitted
818
- # in UDP.
799
+ # *zero-length* data payload, since empty datagrams are permitted in UDP.
819
800
  #
820
- # Connection#send_data is available with UDP packets as with TCP,
801
+ # {Connection#send_data} is available with UDP packets as with TCP,
821
802
  # but there is an important difference. Because UDP communications
822
- # are <i>connectionless,</i> there is no implicit recipient for the packets you
803
+ # are *connectionless*, there is no implicit recipient for the packets you
823
804
  # send. Ordinarily you must specify the recipient for each packet you send.
824
- # However, EventMachine
825
- # provides for the typical pattern of receiving a UDP datagram
805
+ # However, EventMachine provides for the typical pattern of receiving a UDP datagram
826
806
  # from a remote peer, performing some operation, and then sending
827
807
  # one or more packets in response to the same remote peer.
828
- # To support this model easily, just use Connection#send_data
829
- # in the code that you supply for Connection:receive_data.
830
- # EventMachine will
831
- # provide an implicit return address for any messages sent to
832
- # Connection#send_data within the context of a Connection#receive_data callback,
808
+ # To support this model easily, just use {Connection#send_data}
809
+ # in the code that you supply for {Connection#receive_data}.
810
+ #
811
+ # EventMachine will provide an implicit return address for any messages sent to
812
+ # {Connection#send_data} within the context of a {Connection#receive_data} callback,
833
813
  # and your response will automatically go to the correct remote peer.
834
- # (TODO: Example-code needed!)
835
814
  #
836
- # Observe that the port number that you supply to EventMachine#open_datagram_socket
815
+ # Observe that the port number that you supply to {EventMachine.open_datagram_socket}
837
816
  # may be zero. In this case, EventMachine will create a UDP socket
838
- # that is bound to an <i>ephemeral</i> (not well-known) port.
817
+ # that is bound to an [ephemeral port](http://en.wikipedia.org/wiki/Ephemeral_port).
839
818
  # This is not appropriate for servers that must publish a well-known
840
819
  # port to which remote peers may send datagrams. But it can be useful
841
820
  # for clients that send datagrams to other servers.
842
821
  # If you do this, you will receive any responses from the remote
843
- # servers through the normal Connection#receive_data callback.
822
+ # servers through the normal {Connection#receive_data} callback.
844
823
  # Observe that you will probably have issues with firewalls blocking
845
824
  # the ephemeral port numbers, so this technique is most appropriate for LANs.
846
- # (TODO: Need an example!)
847
825
  #
848
826
  # If you wish to send datagrams to arbitrary remote peers (not
849
827
  # necessarily ones that have sent data to which you are responding),
850
- # then see Connection#send_datagram.
828
+ # then see {Connection#send_datagram}.
851
829
  #
852
- # DO NOT call send_data from a datagram socket
853
- # outside of a #receive_data method. Use #send_datagram. If you do use #send_data
854
- # outside of a #receive_data method, you'll get a confusing error
855
- # because there is no "peer," as #send_data requires. (Inside of #receive_data,
856
- # #send_data "fakes" the peer as described above.)
857
- #
858
- #--
859
- # Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
860
- # out that this originally did not take a class but only a module.
830
+ # DO NOT call send_data from a datagram socket outside of a {Connection#receive_data} method. Use {Connection#send_datagram}.
831
+ # If you do use {Connection#send_data} outside of a {Connection#receive_data} method, you'll get a confusing error
832
+ # because there is no "peer," as #send_data requires (inside of {EventMachine::Connection#receive_data},
833
+ # {EventMachine::Connection#send_data} "fakes" the peer as described above).
861
834
  #
835
+ # @param [String] address IP address
836
+ # @param [String] port Port
837
+ # @param [Class, Module] handler A class or a module that implements connection lifecycle callbacks.
862
838
  def self.open_datagram_socket address, port, handler=nil, *args
839
+ # Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
840
+ # out that this originally did not take a class but only a module.
841
+
842
+
863
843
  klass = klass_from_handler(Connection, handler, *args)
864
844
  s = open_udp_socket address, port.to_i
865
845
  c = klass.new s, *args
@@ -871,31 +851,42 @@ module EventMachine
871
851
 
872
852
  # For advanced users. This function sets the default timer granularity, which by default is
873
853
  # slightly smaller than 100 milliseconds. Call this function to set a higher or lower granularity.
874
- # The function affects the behavior of #add_timer and #add_periodic_timer. Most applications
875
- # will not need to call this function.
854
+ # The function affects the behavior of {EventMachine.add_timer} and {EventMachine.add_periodic_timer}.
855
+ # Most applications will not need to call this function.
856
+ #
857
+ # Avoid setting the quantum to very low values because that may reduce performance under some extreme conditions.
858
+ # We recommend that you not use values lower than 10.
876
859
  #
877
- # The argument is a number of milliseconds. Avoid setting the quantum to very low values because
878
- # that may reduce performance under some extreme conditions. We recommend that you not set a quantum
879
- # lower than 10.
860
+ # This method only can be used if event loop is running.
880
861
  #
881
- # You may only call this function while an EventMachine loop is running (that is, after a call to
882
- # EventMachine#run and before a subsequent call to EventMachine#stop).
862
+ # @param [Integer] mills New timer granularity, in milliseconds
883
863
  #
864
+ # @see EventMachine.add_timer
865
+ # @see EventMachine.add_periodic_timer
866
+ # @see EventMachine::Timer
867
+ # @see EventMachine.run
884
868
  def self.set_quantum mills
885
869
  set_timer_quantum mills.to_i
886
870
  end
887
871
 
888
872
  # Sets the maximum number of timers and periodic timers that may be outstanding at any
889
- # given time. You only need to call #set_max_timers if you need more than the default
873
+ # given time. You only need to call {.set_max_timers} if you need more than the default
890
874
  # number of timers, which on most platforms is 1000.
891
- # Call this method before calling EventMachine#run.
892
875
  #
876
+ # @note This method has to be used *before* event loop is started.
877
+ #
878
+ # @param [Integer] ct Maximum number of timers that may be outstanding at any given time
879
+ #
880
+ # @see EventMachine.add_timer
881
+ # @see EventMachine.add_periodic_timer
882
+ # @see EventMachine::Timer
893
883
  def self.set_max_timers ct
894
884
  set_max_timer_count ct
895
885
  end
896
886
 
897
887
  # Gets the current maximum number of allowed timers
898
888
  #
889
+ # @return [Integer] Maximum number of timers that may be outstanding at any given time
899
890
  def self.get_max_timers
900
891
  get_max_timer_count
901
892
  end
@@ -904,35 +895,42 @@ module EventMachine
904
895
  # Note that a tick must pass after the 'initiation' of a connection for this number to increment.
905
896
  # It's usually accurate, but don't rely on the exact precision of this number unless you really know EM internals.
906
897
  #
907
- # For example, $count will be 0 in this case:
898
+ # @example
908
899
  #
909
- # EM.run {
910
- # EM.connect("rubyeventmachine.com", 80)
911
- # $count = EM.connection_count
900
+ # EventMachine.run {
901
+ # EventMachine.connect("rubyeventmachine.com", 80)
902
+ # # count will be 0 in this case, because connection is not
903
+ # # established yet
904
+ # count = EventMachine.connection_count
912
905
  # }
913
906
  #
914
- # In this example, $count will be 1 since the connection has been established in the next loop of the reactor.
915
907
  #
916
- # EM.run {
917
- # EM.connect("rubyeventmachine.com", 80)
918
- # EM.next_tick {
919
- # $count = EM.connection_count
908
+ # @example
909
+ #
910
+ # EventMachine.run {
911
+ # EventMachine.connect("rubyeventmachine.com", 80)
912
+ #
913
+ # EventMachine.next_tick {
914
+ # # In this example, count will be 1 since the connection has been established in
915
+ # # the next loop of the reactor.
916
+ # count = EventMachine.connection_count
920
917
  # }
921
918
  # }
922
919
  #
920
+ # @return [Integer] Number of connections currently held by the reactor.
923
921
  def self.connection_count
924
922
  self.get_connection_count
925
923
  end
926
924
 
927
- #--
928
925
  # The is the responder for the loopback-signalled event.
929
- # It can be fired either by code running on a separate thread (EM#defer) or on
930
- # the main thread (EM#next_tick).
926
+ # It can be fired either by code running on a separate thread ({EventMachine.defer}) or on
927
+ # the main thread ({EventMachine.next_tick}).
931
928
  # It will often happen that a next_tick handler will reschedule itself. We
932
929
  # consume a copy of the tick queue so that tick events scheduled by tick events
933
930
  # have to wait for the next pass through the reactor core.
934
931
  #
935
- def self.run_deferred_callbacks # :nodoc:
932
+ # @private
933
+ def self.run_deferred_callbacks
936
934
  until (@resultqueue ||= []).empty?
937
935
  result,cback = @resultqueue.pop
938
936
  cback.call result if cback
@@ -945,50 +943,53 @@ module EventMachine
945
943
  end
946
944
 
947
945
 
948
- # #defer is for integrating blocking operations into EventMachine's control flow.
949
- # Call #defer with one or two blocks, as shown below (the second block is <i>optional</i>):
950
- #
951
- # operation = proc {
952
- # # perform a long-running operation here, such as a database query.
953
- # "result" # as usual, the last expression evaluated in the block will be the return value.
954
- # }
955
- # callback = proc {|result|
956
- # # do something with result here, such as send it back to a network client.
957
- # }
958
- #
959
- # EventMachine.defer( operation, callback )
960
- #
961
- # The action of #defer is to take the block specified in the first parameter (the "operation")
946
+ # EventMachine.defer is used for integrating blocking operations into EventMachine's control flow.
947
+ # The action of {.defer} is to take the block specified in the first parameter (the "operation")
962
948
  # and schedule it for asynchronous execution on an internal thread pool maintained by EventMachine.
963
949
  # When the operation completes, it will pass the result computed by the block (if any)
964
950
  # back to the EventMachine reactor. Then, EventMachine calls the block specified in the
965
- # second parameter to #defer (the "callback"), as part of its normal, synchronous
966
- # event handling loop. The result computed by the operation block is passed as a parameter
967
- # to the callback. You may omit the callback parameter if you don't need to execute any code
968
- # after the operation completes.
951
+ # second parameter to {.defer} (the "callback"), as part of its normal event handling loop.
952
+ # The result computed by the operation block is passed as a parameter to the callback.
953
+ # You may omit the callback parameter if you don't need to execute any code after the operation completes.
954
+ #
955
+ # ## Caveats ##
969
956
  #
970
- # == Caveats
971
957
  # Note carefully that the code in your deferred operation will be executed on a separate
972
958
  # thread from the main EventMachine processing and all other Ruby threads that may exist in
973
959
  # your program. Also, multiple deferred operations may be running at once! Therefore, you
974
- # are responsible for ensuring that your operation code is threadsafe. [Need more explanation
975
- # and examples.]
960
+ # are responsible for ensuring that your operation code is threadsafe.
961
+ #
976
962
  # Don't write a deferred operation that will block forever. If so, the current implementation will
977
963
  # not detect the problem, and the thread will never be returned to the pool. EventMachine limits
978
964
  # the number of threads in its pool, so if you do this enough times, your subsequent deferred
979
- # operations won't get a chance to run. [We might put in a timer to detect this problem.]
965
+ # operations won't get a chance to run.
966
+ #
967
+ # @example
968
+ #
969
+ # operation = proc {
970
+ # # perform a long-running operation here, such as a database query.
971
+ # "result" # as usual, the last expression evaluated in the block will be the return value.
972
+ # }
973
+ # callback = proc {|result|
974
+ # # do something with result here, such as send it back to a network client.
975
+ # }
980
976
  #
981
- #--
982
- # OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here
983
- # without syncing there.
977
+ # EventMachine.defer(operation, callback)
984
978
  #
985
- # Running with $VERBOSE set to true gives a warning unless all ivars are defined when
986
- # they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we
987
- # need it, because the Ruby threads are so heavyweight. We end up with this bizarre
988
- # way of initializing @threadqueue because EventMachine is a Module, not a Class, and
989
- # has no constructor.
979
+ # @param [#call] op An operation you want to offload to EventMachine thread pool
980
+ # @param [#call] callback A callback that will be run on the event loop thread after `operation` finishes.
990
981
  #
982
+ # @see EventMachine.threadpool_size
991
983
  def self.defer op = nil, callback = nil, &blk
984
+ # OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here
985
+ # without syncing there.
986
+ #
987
+ # Running with $VERBOSE set to true gives a warning unless all ivars are defined when
988
+ # they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we
989
+ # need it, because the Ruby threads are so heavyweight. We end up with this bizarre
990
+ # way of initializing @threadqueue because EventMachine is a Module, not a Class, and
991
+ # has no constructor.
992
+
992
993
  unless @threadpool
993
994
  require 'thread'
994
995
  @threadpool = []
@@ -1000,7 +1001,9 @@ module EventMachine
1000
1001
  @threadqueue << [op||blk,callback]
1001
1002
  end
1002
1003
 
1003
- def self.spawn_threadpool # :nodoc:
1004
+
1005
+ # @private
1006
+ def self.spawn_threadpool
1004
1007
  until @threadpool.size == @threadpool_size.to_i
1005
1008
  thread = Thread.new do
1006
1009
  Thread.current.abort_on_exception = true
@@ -1016,9 +1019,11 @@ module EventMachine
1016
1019
  end
1017
1020
 
1018
1021
  class << self
1019
- attr_reader :threadpool # :nodoc:
1022
+ # @private
1023
+ attr_reader :threadpool
1020
1024
 
1021
1025
  # Size of the EventMachine.defer threadpool (defaults to 20)
1026
+ # @return [Number]
1022
1027
  attr_accessor :threadpool_size
1023
1028
  EventMachine.threadpool_size = 20
1024
1029
  end
@@ -1026,19 +1031,20 @@ module EventMachine
1026
1031
  # Schedules a proc for execution immediately after the next "turn" through the reactor
1027
1032
  # core. An advanced technique, this can be useful for improving memory management and/or
1028
1033
  # application responsiveness, especially when scheduling large amounts of data for
1029
- # writing to a network connection. TODO, we need a FAQ entry on this subject.
1030
- #
1031
- # #next_tick takes either a single argument (which must be a Proc) or a block.
1032
- #--
1033
- # This works by adding to the @resultqueue that's used for #defer.
1034
- # The general idea is that next_tick is used when we want to give the reactor a chance
1035
- # to let other operations run, either to balance the load out more evenly, or to let
1036
- # outbound network buffers drain, or both. So we probably do NOT want to block, and
1037
- # we probably do NOT want to be spinning any threads. A program that uses next_tick
1038
- # but not #defer shouldn't suffer the penalty of having Ruby threads running. They're
1039
- # extremely expensive even if they're just sleeping.
1034
+ # writing to a network connection.
1040
1035
  #
1036
+ # This method takes either a single argument (which must be a callable object) or a block.
1037
+ #
1038
+ # @param [#call] pr A callable object to run
1041
1039
  def self.next_tick pr=nil, &block
1040
+ # This works by adding to the @resultqueue that's used for #defer.
1041
+ # The general idea is that next_tick is used when we want to give the reactor a chance
1042
+ # to let other operations run, either to balance the load out more evenly, or to let
1043
+ # outbound network buffers drain, or both. So we probably do NOT want to block, and
1044
+ # we probably do NOT want to be spinning any threads. A program that uses next_tick
1045
+ # but not #defer shouldn't suffer the penalty of having Ruby threads running. They're
1046
+ # extremely expensive even if they're just sleeping.
1047
+
1042
1048
  raise ArgumentError, "no proc or block given" unless ((pr && pr.respond_to?(:call)) or block)
1043
1049
  @next_tick_mutex.synchronize do
1044
1050
  @next_tick_queue << ( pr || block )
@@ -1048,42 +1054,44 @@ module EventMachine
1048
1054
 
1049
1055
  # A wrapper over the setuid system call. Particularly useful when opening a network
1050
1056
  # server on a privileged port because you can use this call to drop privileges
1051
- # after opening the port. Also very useful after a call to #set_descriptor_table_size,
1057
+ # after opening the port. Also very useful after a call to {.set_descriptor_table_size},
1052
1058
  # which generally requires that you start your process with root privileges.
1053
1059
  #
1054
- # This method has no effective implementation on Windows or in the pure-Ruby
1055
- # implementation of EventMachine.
1056
- # Call #set_effective_user by passing it a string containing the effective name
1057
- # of the user whose privilege-level your process should attain.
1058
1060
  # This method is intended for use in enforcing security requirements, consequently
1059
1061
  # it will throw a fatal error and end your program if it fails.
1060
1062
  #
1063
+ # @param [String] username The effective name of the user whose privilege-level your process should attain.
1064
+ #
1065
+ # @note This method has no effective implementation on Windows or in the pure-Ruby
1066
+ # implementation of EventMachine
1061
1067
  def self.set_effective_user username
1062
1068
  EventMachine::setuid_string username
1063
1069
  end
1064
1070
 
1065
1071
 
1066
1072
  # Sets the maximum number of file or socket descriptors that your process may open.
1067
- # You can pass this method an integer specifying the new size of the descriptor table.
1068
- # Returns the new descriptor-table size, which may be less than the number you
1069
- # requested. If you call this method with no arguments, it will simply return
1073
+ # If you call this method with no arguments, it will simply return
1070
1074
  # the current size of the descriptor table without attempting to change it.
1071
1075
  #
1072
- # The new limit on open descriptors ONLY applies to sockets and other descriptors
1073
- # that belong to EventMachine. It has NO EFFECT on the number of descriptors
1076
+ # The new limit on open descriptors **only** applies to sockets and other descriptors
1077
+ # that belong to EventMachine. It has **no effect** on the number of descriptors
1074
1078
  # you can create in ordinary Ruby code.
1075
1079
  #
1076
1080
  # Not available on all platforms. Increasing the number of descriptors beyond its
1077
- # default limit usually requires superuser privileges. (See #set_effective_user
1081
+ # default limit usually requires superuser privileges. (See {.set_effective_user}
1078
1082
  # for a way to drop superuser privileges while your program is running.)
1079
1083
  #
1084
+ # @param [Integer] n_descriptors The maximum number of file or socket descriptors that your process may open
1085
+ # @return [Integer] The new descriptor table size.
1080
1086
  def self.set_descriptor_table_size n_descriptors=nil
1081
1087
  EventMachine::set_rlimit_nofile n_descriptors
1082
1088
  end
1083
1089
 
1084
1090
 
1085
1091
 
1086
- # Run an external process. This does not currently work on Windows.
1092
+ # Runs an external process.
1093
+ #
1094
+ # @example
1087
1095
  #
1088
1096
  # module RubyCounter
1089
1097
  # def post_init
@@ -1098,16 +1106,17 @@ module EventMachine
1098
1106
  # end
1099
1107
  # end
1100
1108
  #
1101
- # EM.run{
1102
- # EM.popen("ruby -e' $stdout.sync = true; gets.to_i.times{ |i| puts i+1; sleep 1 } '", RubyCounter)
1109
+ # EventMachine.run {
1110
+ # EventMachine.popen("ruby -e' $stdout.sync = true; gets.to_i.times{ |i| puts i+1; sleep 1 } '", RubyCounter)
1103
1111
  # }
1104
1112
  #
1105
- # Also see EventMachine::DeferrableChildProcess and EventMachine.system
1106
- #--
1107
- # At this moment, it's only available on Unix.
1108
- # Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
1109
- #
1113
+ # @note This method is not supported on Microsoft Windows
1114
+ # @see EventMachine::DeferrableChildProcess
1115
+ # @see EventMachine.system
1110
1116
  def self.popen cmd, handler=nil, *args
1117
+ # At this moment, it's only available on Unix.
1118
+ # Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
1119
+
1111
1120
  klass = klass_from_handler(Connection, handler, *args)
1112
1121
  w = Shellwords::shellwords( cmd )
1113
1122
  w.unshift( w.first ) if w.first
@@ -1119,16 +1128,15 @@ module EventMachine
1119
1128
  end
1120
1129
 
1121
1130
 
1122
- # Tells you whether the EventMachine reactor loop is currently running. Returns true or
1123
- # false. Useful when writing libraries that want to run event-driven code, but may
1124
- # be running in programs that are already event-driven. In such cases, if EventMachine#reactor_running?
1125
- # returns false, your code can invoke EventMachine#run and run your application code inside
1126
- # the block passed to that method. If EventMachine#reactor_running? returns true, just
1127
- # execute your event-aware code.
1131
+ # Tells you whether the EventMachine reactor loop is currently running.
1128
1132
  #
1129
- # This method is necessary because calling EventMachine#run inside of another call to
1130
- # EventMachine#run generates a fatal error.
1133
+ # Useful when writing libraries that want to run event-driven code, but may
1134
+ # be running in programs that are already event-driven. In such cases, if {EventMachine.reactor_running?}
1135
+ # returns false, your code can invoke {EventMachine.run} and run your application code inside
1136
+ # the block passed to that method. If this method returns true, just
1137
+ # execute your event-aware code.
1131
1138
  #
1139
+ # @return [Boolean] true if the EventMachine reactor loop is currently running
1132
1140
  def self.reactor_running?
1133
1141
  (@reactor_running || false)
1134
1142
  end
@@ -1136,7 +1144,7 @@ module EventMachine
1136
1144
 
1137
1145
  # (Experimental)
1138
1146
  #
1139
- #
1147
+ # @private
1140
1148
  def self.open_keyboard handler=nil, *args
1141
1149
  klass = klass_from_handler(Connection, handler, *args)
1142
1150
 
@@ -1148,7 +1156,7 @@ module EventMachine
1148
1156
  end
1149
1157
 
1150
1158
  # EventMachine's file monitoring API. Currently supported are the following events
1151
- # on individual files, using inotify on Linux systems, and kqueue for OSX/BSD:
1159
+ # on individual files, using inotify on Linux systems, and kqueue for *BSD and Mac OS X:
1152
1160
  #
1153
1161
  # * File modified (written to)
1154
1162
  # * File moved/renamed
@@ -1156,26 +1164,26 @@ module EventMachine
1156
1164
  #
1157
1165
  # EventMachine::watch_file takes a filename and a handler Module containing your custom callback methods.
1158
1166
  # This will setup the low level monitoring on the specified file, and create a new EventMachine::FileWatch
1159
- # object with your Module mixed in. FileWatch is a subclass of EM::Connection, so callbacks on this object
1167
+ # object with your Module mixed in. FileWatch is a subclass of {EventMachine::Connection}, so callbacks on this object
1160
1168
  # work in the familiar way. The callbacks that will be fired by EventMachine are:
1161
1169
  #
1162
1170
  # * file_modified
1163
1171
  # * file_moved
1164
1172
  # * file_deleted
1165
1173
  #
1166
- # You can access the filename being monitored from within this object using FileWatch#path.
1174
+ # You can access the filename being monitored from within this object using {FileWatch#path}.
1167
1175
  #
1168
- # When a file is deleted, FileWatch#stop_watching will be called after your file_deleted callback,
1169
- # to clean up the underlying monitoring and remove EventMachine's reference to the now-useless FileWatch.
1176
+ # When a file is deleted, {FileWatch#stop_watching} will be called after your file_deleted callback,
1177
+ # to clean up the underlying monitoring and remove EventMachine's reference to the now-useless {FileWatch} instance.
1170
1178
  # This will in turn call unbind, if you wish to use it.
1171
1179
  #
1172
1180
  # The corresponding system-level Errno will be raised when attempting to monitor non-existent files,
1173
1181
  # files with wrong permissions, or if an error occurs dealing with inotify/kqueue.
1174
1182
  #
1175
- # === Usage example:
1183
+ # @example
1176
1184
  #
1177
- # Make sure we have a file to monitor:
1178
- # $ echo "bar" > /tmp/foo
1185
+ # # Before running this example, make sure we have a file to monitor:
1186
+ # # $ echo "bar" > /tmp/foo
1179
1187
  #
1180
1188
  # module Handler
1181
1189
  # def file_modified
@@ -1195,20 +1203,22 @@ module EventMachine
1195
1203
  # end
1196
1204
  # end
1197
1205
  #
1198
- # EM.kqueue = true if EM.kqueue? # file watching requires kqueue on OSX
1206
+ # # for efficient file watching, use kqueue on Mac OS X
1207
+ # EventMachine.kqueue = true if EventMachine.kqueue?
1199
1208
  #
1200
- # EM.run {
1201
- # EM.watch_file("/tmp/foo", Handler)
1209
+ # EventMachine.run {
1210
+ # EventMachine.watch_file("/tmp/foo", Handler)
1202
1211
  # }
1203
1212
  #
1204
- # $ echo "baz" >> /tmp/foo => "/tmp/foo modified"
1205
- # $ mv /tmp/foo /tmp/oof => "/tmp/foo moved"
1206
- # $ rm /tmp/oof => "/tmp/foo deleted"
1207
- # => "/tmp/foo monitoring ceased"
1213
+ # # $ echo "baz" >> /tmp/foo => "/tmp/foo modified"
1214
+ # # $ mv /tmp/foo /tmp/oof => "/tmp/foo moved"
1215
+ # # $ rm /tmp/oof => "/tmp/foo deleted"
1208
1216
  #
1209
- # Note that we have not implemented the ability to pick up on the new filename after a rename.
1210
- # Calling #path will always return the filename you originally used.
1217
+ # @note The ability to pick up on the new filename after a rename is not yet supported.
1218
+ # Calling #path will always return the filename you originally used.
1211
1219
  #
1220
+ # @param [String] filename Local path to the file to watch.
1221
+ # @param [Class, Module] handler A class or module that implements event handlers associated with the file.
1212
1222
  def self.watch_file(filename, handler=nil, *args)
1213
1223
  klass = klass_from_handler(FileWatch, handler, *args)
1214
1224
 
@@ -1221,9 +1231,9 @@ module EventMachine
1221
1231
  c
1222
1232
  end
1223
1233
 
1224
- # EventMachine's process monitoring API. Currently supported using kqueue for OSX/BSD.
1234
+ # EventMachine's process monitoring API. On Mac OS X and *BSD this method is implemented using kqueue.
1225
1235
  #
1226
- # === Usage example:
1236
+ # @example
1227
1237
  #
1228
1238
  # module ProcessWatcher
1229
1239
  # def process_exited
@@ -1233,11 +1243,13 @@ module EventMachine
1233
1243
  #
1234
1244
  # pid = fork{ sleep }
1235
1245
  #
1236
- # EM.run{
1237
- # EM.watch_process(pid, ProcessWatcher)
1238
- # EM.add_timer(1){ Process.kill('TERM', pid) }
1246
+ # EventMachine.run {
1247
+ # EventMachine.watch_process(pid, ProcessWatcher)
1248
+ # EventMachine.add_timer(1){ Process.kill('TERM', pid) }
1239
1249
  # }
1240
1250
  #
1251
+ # @param [Integer] pid PID of the process to watch.
1252
+ # @param [Class, Module] handler A class or module that implements event handlers associated with the file.
1241
1253
  def self.watch_process(pid, handler=nil, *args)
1242
1254
  pid = pid.to_i
1243
1255
 
@@ -1254,10 +1266,13 @@ module EventMachine
1254
1266
 
1255
1267
  # Catch-all for errors raised during event loop callbacks.
1256
1268
  #
1257
- # EM.error_handler{ |e|
1258
- # puts "Error raised during event loop: #{e.message}"
1259
- # }
1269
+ # @example
1260
1270
  #
1271
+ # EventMachine.error_handler{ |e|
1272
+ # puts "Error raised during event loop: #{e.message}"
1273
+ # }
1274
+ #
1275
+ # @param [#call] cb Global catch-all errback
1261
1276
  def self.error_handler cb = nil, &blk
1262
1277
  if cb or blk
1263
1278
  @error_handler = cb || blk
@@ -1266,12 +1281,12 @@ module EventMachine
1266
1281
  end
1267
1282
  end
1268
1283
 
1269
- # enable_proxy allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor.
1270
- # This is especially useful for proxies where high performance is required. Propogating data from a server response
1284
+ # This method allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor.
1285
+ # This is very efficient and especially useful for proxies where high performance is required. Propogating data from a server response
1271
1286
  # all the way up to Ruby, and then back down to the reactor to be sent back to the client, is often unnecessary and
1272
1287
  # incurs a significant performance decrease.
1273
1288
  #
1274
- # The two arguments are Connections, 'from' and 'to'. 'from' is the connection whose inbound data you want
1289
+ # The two arguments are instance of {EventMachine::Connection} subclasses, 'from' and 'to'. 'from' is the connection whose inbound data you want
1275
1290
  # relayed back out. 'to' is the connection to write it to.
1276
1291
  #
1277
1292
  # Once you call this method, the 'from' connection will no longer get receive_data callbacks from the reactor,
@@ -1279,10 +1294,10 @@ module EventMachine
1279
1294
  # in the example, that proxy_target_unbound will be called when this occurs. After that, further incoming
1280
1295
  # data will be passed into receive_data as normal.
1281
1296
  #
1282
- # Note also that this feature supports different types of descriptors - TCP, UDP, and pipes. You can relay
1283
- # data from one kind to another.
1297
+ # Note also that this feature supports different types of descriptors: TCP, UDP, and pipes. You can relay
1298
+ # data from one kind to another, for example, feed a pipe from a UDP stream.
1284
1299
  #
1285
- # Example:
1300
+ # @example
1286
1301
  #
1287
1302
  # module ProxyConnection
1288
1303
  # def initialize(client, request)
@@ -1310,42 +1325,55 @@ module EventMachine
1310
1325
  # def receive_data(data)
1311
1326
  # (@buf ||= "") << data
1312
1327
  # if @buf =~ /\r\n\r\n/ # all http headers received
1313
- # EM.connect("10.0.0.15", 80, ProxyConnection, self, data)
1328
+ # EventMachine.connect("10.0.0.15", 80, ProxyConnection, self, data)
1314
1329
  # end
1315
1330
  # end
1316
1331
  # end
1317
1332
  #
1318
- # EM.run {
1319
- # EM.start_server("127.0.0.1", 8080, ProxyServer)
1333
+ # EventMachine.run {
1334
+ # EventMachine.start_server("127.0.0.1", 8080, ProxyServer)
1320
1335
  # }
1336
+ #
1337
+ # @param [EventMachine::Connection] from Source of data to be proxies/streamed.
1338
+ # @param [EventMachine::Connection] to Destination of data to be proxies/streamed.
1339
+ # @param [Integer] bufsize Buffer size to use
1340
+ # @param [Integer] length Maximum number of bytes to proxy.
1341
+ #
1342
+ # @see EventMachine.disable_proxy
1321
1343
  def self.enable_proxy(from, to, bufsize=0, length=0)
1322
1344
  EM::start_proxy(from.signature, to.signature, bufsize, length)
1323
1345
  end
1324
1346
 
1325
- # disable_proxy takes just one argument, a Connection that has proxying enabled via enable_proxy.
1347
+ # Takes just one argument, a {Connection} that has proxying enabled via {EventMachine.enable_proxy}.
1326
1348
  # Calling this method will remove that functionality and your connection will begin receiving
1327
- # data via receive_data again.
1349
+ # data via {Connection#receive_data} again.
1350
+ #
1351
+ # @param [EventMachine::Connection] from Source of data that is being proxied
1352
+ # @see EventMachine.enable_proxy
1328
1353
  def self.disable_proxy(from)
1329
1354
  EM::stop_proxy(from.signature)
1330
1355
  end
1331
1356
 
1332
1357
  # Retrieve the heartbeat interval. This is how often EventMachine will check for dead connections
1333
- # that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout.
1358
+ # that have had an inactivity timeout set via {Connection#set_comm_inactivity_timeout}.
1334
1359
  # Default is 2 seconds.
1360
+ #
1361
+ # @return [Integer] Heartbeat interval, in seconds
1335
1362
  def self.heartbeat_interval
1336
1363
  EM::get_heartbeat_interval
1337
1364
  end
1338
1365
 
1339
1366
  # Set the heartbeat interval. This is how often EventMachine will check for dead connections
1340
- # that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout.
1367
+ # that have had an inactivity timeout set via {Connection#set_comm_inactivity_timeout}.
1341
1368
  # Takes a Numeric number of seconds. Default is 2.
1342
- def self.heartbeat_interval= (time)
1369
+ #
1370
+ # @param [Integer] time Heartbeat interval, in seconds
1371
+ def self.heartbeat_interval=(time)
1343
1372
  EM::set_heartbeat_interval time.to_f
1344
1373
  end
1345
1374
 
1346
- private
1347
-
1348
- def self.event_callback conn_binding, opcode, data # :nodoc:
1375
+ # @private
1376
+ def self.event_callback conn_binding, opcode, data
1349
1377
  #
1350
1378
  # Changed 27Dec07: Eliminated the hookable error handling.
1351
1379
  # No one was using it, and it degraded performance significantly.
@@ -1363,7 +1391,11 @@ module EventMachine
1363
1391
  if opcode == ConnectionUnbound
1364
1392
  if c = @conns.delete( conn_binding )
1365
1393
  begin
1366
- c.unbind
1394
+ if c.original_method(:unbind).arity == 1
1395
+ c.unbind(data == 0 ? nil : EventMachine::ERRNOS[data])
1396
+ else
1397
+ c.unbind
1398
+ end
1367
1399
  rescue
1368
1400
  @wrapped_exception = $!
1369
1401
  stop
@@ -1385,9 +1417,9 @@ module EventMachine
1385
1417
  @conns[data] = c
1386
1418
  blk and blk.call(c)
1387
1419
  c # (needed?)
1388
- ##
1389
- # The remaining code is a fallback for the pure ruby and java reactors.
1390
- # In the C++ reactor, these events are handled in the C event_callback() in rubymain.cpp
1420
+ ##
1421
+ # The remaining code is a fallback for the pure ruby and java reactors.
1422
+ # In the C++ reactor, these events are handled in the C event_callback() in rubymain.cpp
1391
1423
  elsif opcode == ConnectionCompleted
1392
1424
  c = @conns[conn_binding] or raise ConnectionNotBound, "received ConnectionCompleted for unknown signature: #{conn_binding}"
1393
1425
  c.connection_completed
@@ -1410,107 +1442,10 @@ module EventMachine
1410
1442
  end
1411
1443
  end
1412
1444
 
1413
- #--
1414
- # The original event_callback below handled runtime errors in ruby and degraded performance significantly.
1415
- # An optional C-based error handler is now available via EM::error_handler
1416
- #
1417
- # private
1418
- # def EventMachine::original_event_callback conn_binding, opcode, data
1419
- # #
1420
- # # Added 03Oct07: Any code path that invokes user-written code must
1421
- # # wrap itself in a begin/rescue for RuntimeErrors, that calls the
1422
- # # user-overridable class method #handle_runtime_error.
1423
- # #
1424
- # if opcode == ConnectionData
1425
- # c = @conns[conn_binding] or raise ConnectionNotBound
1426
- # begin
1427
- # c.receive_data data
1428
- # rescue
1429
- # EventMachine.handle_runtime_error
1430
- # end
1431
- # elsif opcode == ConnectionUnbound
1432
- # if c = @conns.delete( conn_binding )
1433
- # begin
1434
- # c.unbind
1435
- # rescue
1436
- # EventMachine.handle_runtime_error
1437
- # end
1438
- # elsif c = @acceptors.delete( conn_binding )
1439
- # # no-op
1440
- # else
1441
- # raise ConnectionNotBound
1442
- # end
1443
- # elsif opcode == ConnectionAccepted
1444
- # accep,args,blk = @acceptors[conn_binding]
1445
- # raise NoHandlerForAcceptedConnection unless accep
1446
- # c = accep.new data, *args
1447
- # @conns[data] = c
1448
- # begin
1449
- # blk and blk.call(c)
1450
- # rescue
1451
- # EventMachine.handle_runtime_error
1452
- # end
1453
- # c # (needed?)
1454
- # elsif opcode == TimerFired
1455
- # t = @timers.delete( data ) or raise UnknownTimerFired
1456
- # begin
1457
- # t.call
1458
- # rescue
1459
- # EventMachine.handle_runtime_error
1460
- # end
1461
- # elsif opcode == ConnectionCompleted
1462
- # c = @conns[conn_binding] or raise ConnectionNotBound
1463
- # begin
1464
- # c.connection_completed
1465
- # rescue
1466
- # EventMachine.handle_runtime_error
1467
- # end
1468
- # elsif opcode == LoopbreakSignalled
1469
- # begin
1470
- # run_deferred_callbacks
1471
- # rescue
1472
- # EventMachine.handle_runtime_error
1473
- # end
1474
- # end
1475
- # end
1476
- #
1477
- #
1478
- # # Default handler for RuntimeErrors that are raised in user code.
1479
- # # The default behavior is to re-raise the error, which ends your program.
1480
- # # To override the default behavior, re-implement this method in your code.
1481
- # # For example:
1482
- # #
1483
- # # module EventMachine
1484
- # # def self.handle_runtime_error
1485
- # # $>.puts $!
1486
- # # end
1487
- # # end
1488
- # #
1489
- # #--
1490
- # # We need to ensure that any code path which invokes user code rescues RuntimeError
1491
- # # and calls this method. The obvious place to do that is in #event_callback,
1492
- # # but, scurrilously, it turns out that we need to be finer grained that that.
1493
- # # Periodic timers, in particular, wrap their invocations of user code inside
1494
- # # procs that do other stuff we can't not do, like schedule the next invocation.
1495
- # # This is a potential non-robustness, since we need to remember to hook in the
1496
- # # error handler whenever and wherever we change how user code is invoked.
1497
- # #
1498
- # def EventMachine::handle_runtime_error
1499
- # @runtime_error_hook ? @runtime_error_hook.call : raise
1500
- # end
1501
- #
1502
- # # Sets a handler for RuntimeErrors that are raised in user code.
1503
- # # Pass a block with no parameters. You can also call this method without a block,
1504
- # # which restores the default behavior (see #handle_runtime_error).
1505
- # #
1506
- # def EventMachine::set_runtime_error_hook &blk
1507
- # @runtime_error_hook = blk
1508
- # end
1509
-
1510
- #--
1511
- # This is a provisional implementation of a stream-oriented file access object.
1512
- # We also experiment with wrapping up some better exception reporting.
1513
- def self._open_file_for_writing filename, handler=nil # :nodoc:
1445
+ #
1446
+ #
1447
+ # @private
1448
+ def self._open_file_for_writing filename, handler=nil
1514
1449
  klass = klass_from_handler(Connection, handler)
1515
1450
 
1516
1451
  s = _write_file filename
@@ -1520,7 +1455,7 @@ module EventMachine
1520
1455
  c
1521
1456
  end
1522
1457
 
1523
- private
1458
+ # @private
1524
1459
  def self.klass_from_handler(klass = Connection, handler = nil, *args)
1525
1460
  klass = if handler and handler.is_a?(Class)
1526
1461
  raise ArgumentError, "must provide module or subclass of #{klass.name}" unless klass >= handler
@@ -1545,6 +1480,7 @@ module EventMachine
1545
1480
  end
1546
1481
  end # module EventMachine
1547
1482
 
1548
- # Save everyone some typing.
1483
+ # Alias for {EventMachine}
1549
1484
  EM = EventMachine
1485
+ # Alias for {EventMachine::Protocols}
1550
1486
  EM::P = EventMachine::Protocols