MattHulse-eventmachine 0.0.1

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