brianmario-eventmachine 0.12.2

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 (72) hide show
  1. data/COPYING +60 -0
  2. data/DEFERRABLES +138 -0
  3. data/EPOLL +141 -0
  4. data/GNU +281 -0
  5. data/KEYBOARD +38 -0
  6. data/LEGAL +25 -0
  7. data/LIGHTWEIGHT_CONCURRENCY +72 -0
  8. data/PURE_RUBY +77 -0
  9. data/README +74 -0
  10. data/RELEASE_NOTES +96 -0
  11. data/SMTP +9 -0
  12. data/SPAWNED_PROCESSES +93 -0
  13. data/TODO +10 -0
  14. data/eventmachine.gemspec +15 -0
  15. data/ext/binder.cpp +126 -0
  16. data/ext/binder.h +48 -0
  17. data/ext/cmain.cpp +553 -0
  18. data/ext/cplusplus.cpp +172 -0
  19. data/ext/ed.cpp +1473 -0
  20. data/ext/ed.h +361 -0
  21. data/ext/em.cpp +1890 -0
  22. data/ext/em.h +170 -0
  23. data/ext/emwin.cpp +300 -0
  24. data/ext/emwin.h +94 -0
  25. data/ext/epoll.cpp +26 -0
  26. data/ext/epoll.h +25 -0
  27. data/ext/eventmachine.h +90 -0
  28. data/ext/eventmachine_cpp.h +94 -0
  29. data/ext/extconf.rb +203 -0
  30. data/ext/files.cpp +94 -0
  31. data/ext/files.h +65 -0
  32. data/ext/kb.cpp +368 -0
  33. data/ext/page.cpp +107 -0
  34. data/ext/page.h +51 -0
  35. data/ext/pipe.cpp +327 -0
  36. data/ext/project.h +119 -0
  37. data/ext/rubymain.cpp +678 -0
  38. data/ext/sigs.cpp +89 -0
  39. data/ext/sigs.h +32 -0
  40. data/ext/ssl.cpp +408 -0
  41. data/ext/ssl.h +86 -0
  42. data/lib/em/deferrable.rb +208 -0
  43. data/lib/em/eventable.rb +39 -0
  44. data/lib/em/future.rb +62 -0
  45. data/lib/em/messages.rb +66 -0
  46. data/lib/em/processes.rb +68 -0
  47. data/lib/em/spawnable.rb +88 -0
  48. data/lib/em/streamer.rb +112 -0
  49. data/lib/eventmachine.rb +1756 -0
  50. data/lib/eventmachine_version.rb +31 -0
  51. data/lib/evma.rb +32 -0
  52. data/lib/evma/callback.rb +32 -0
  53. data/lib/evma/container.rb +75 -0
  54. data/lib/evma/factory.rb +77 -0
  55. data/lib/evma/protocol.rb +87 -0
  56. data/lib/evma/reactor.rb +48 -0
  57. data/lib/jeventmachine.rb +132 -0
  58. data/lib/pr_eventmachine.rb +1011 -0
  59. data/lib/protocols/buftok.rb +127 -0
  60. data/lib/protocols/header_and_content.rb +129 -0
  61. data/lib/protocols/httpcli2.rb +784 -0
  62. data/lib/protocols/httpclient.rb +264 -0
  63. data/lib/protocols/line_and_text.rb +122 -0
  64. data/lib/protocols/linetext2.rb +163 -0
  65. data/lib/protocols/postgres.rb +261 -0
  66. data/lib/protocols/saslauth.rb +179 -0
  67. data/lib/protocols/smtpclient.rb +308 -0
  68. data/lib/protocols/smtpserver.rb +543 -0
  69. data/lib/protocols/stomp.rb +130 -0
  70. data/lib/protocols/tcptest.rb +57 -0
  71. data/setup.rb +1585 -0
  72. metadata +126 -0
@@ -0,0 +1,68 @@
1
+ # $Id$
2
+ #
3
+ # Author:: Francis Cianfrocca (gmail: blackhedd)
4
+ # Homepage:: http://rubyeventmachine.com
5
+ # Date:: 13 Dec 07
6
+ #
7
+ # See EventMachine and EventMachine::Connection for documentation and
8
+ # usage examples.
9
+ #
10
+ #----------------------------------------------------------------------------
11
+ #
12
+ # Copyright (C) 2006-08 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
+ module EventMachine
28
+
29
+ # EM::DeferrableChildProcess is a sugaring of a common use-case
30
+ # involving EM::popen.
31
+ # Call the #open method on EM::DeferrableChildProcess, passing
32
+ # a command-string. #open immediately returns an EM::Deferrable
33
+ # object. It also schedules the forking of a child process, which
34
+ # will execute the command passed to #open.
35
+ # When the forked child terminates, the Deferrable will be signalled
36
+ # and execute its callbacks, passing the data that the child process
37
+ # wrote to stdout.
38
+ #
39
+ class DeferrableChildProcess < EventMachine::Connection
40
+ include EventMachine::Deferrable
41
+
42
+ # Sugars a common use-case involving forked child processes.
43
+ # #open takes a String argument containing an shell command
44
+ # string (including arguments if desired). #open immediately
45
+ # returns an EventMachine::Deferrable object, without blocking.
46
+ #
47
+ # It also invokes EventMachine#popen to run the passed-in
48
+ # command in a forked child process.
49
+ #
50
+ # When the forked child terminates, the Deferrable that
51
+ # #open calls its callbacks, passing the data returned
52
+ # from the child process.
53
+ #
54
+ def self.open cmd
55
+ EventMachine.popen( cmd, DeferrableChildProcess )
56
+ end
57
+
58
+ def receive_data data
59
+ (@data ||= []) << data
60
+ end
61
+
62
+ def unbind
63
+ succeed( @data.join )
64
+ end
65
+ end
66
+ end
67
+
68
+
@@ -0,0 +1,88 @@
1
+ # $Id$
2
+ #
3
+ # Author:: Francis Cianfrocca (gmail: blackhedd)
4
+ # Homepage:: http://rubyeventmachine.com
5
+ # Date:: 25 Aug 2007
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
+ # Support for Erlang-style processes.
28
+ #
29
+
30
+
31
+ module EventMachine
32
+ class SpawnedProcess
33
+ #attr_accessor :receiver
34
+ def notify *x
35
+ me = self
36
+ EM.next_tick {
37
+ # A notification executes in the context of this
38
+ # SpawnedProcess object. That makes self and notify
39
+ # work as one would expect.
40
+ #
41
+ y = me.call(*x)
42
+ if y and y.respond_to?(:pull_out_yield_block)
43
+ a,b = y.pull_out_yield_block
44
+ set_receiver a
45
+ self.notify if b
46
+ end
47
+ }
48
+ end
49
+ alias_method :resume, :notify
50
+ alias_method :run, :notify # for formulations like (EM.spawn {xxx}).run
51
+
52
+ # I know I'm missing something stupid, but the inside of class << s
53
+ # can't see locally-bound values. It can see globals, though.
54
+ def set_receiver blk
55
+ $em______tmpglobal = blk
56
+ class << self
57
+ define_method :call, $em______tmpglobal.dup
58
+ end
59
+ end
60
+
61
+ end
62
+
63
+ class YieldBlockFromSpawnedProcess
64
+ def initialize block, notify
65
+ @block = [block,notify]
66
+ end
67
+ def pull_out_yield_block
68
+ @block
69
+ end
70
+ end
71
+
72
+ def EventMachine.spawn &block
73
+ s = SpawnedProcess.new
74
+ s.set_receiver block
75
+ s
76
+ end
77
+
78
+ def EventMachine.yield &block
79
+ return YieldBlockFromSpawnedProcess.new( block, false )
80
+ end
81
+
82
+ def EventMachine.yield_and_notify &block
83
+ return YieldBlockFromSpawnedProcess.new( block, true )
84
+ end
85
+ end
86
+
87
+
88
+
@@ -0,0 +1,112 @@
1
+ # $Id$
2
+ #
3
+ # Author:: Francis Cianfrocca (gmail: blackhedd)
4
+ # Homepage:: http://rubyeventmachine.com
5
+ # Date:: 16 Jul 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
+ module EventMachine
28
+ class FileStreamer
29
+ MappingThreshold = 16384
30
+ BackpressureLevel = 50000
31
+ ChunkSize = 16384
32
+
33
+ include Deferrable
34
+ def initialize connection, filename, args
35
+ @connection = connection
36
+ @http_chunks = args[:http_chunks]
37
+
38
+ if File.exist?(filename)
39
+ @size = File.size?(filename)
40
+ if @size <= MappingThreshold
41
+ stream_without_mapping filename
42
+ else
43
+ stream_with_mapping filename
44
+ end
45
+ else
46
+ fail "file not found"
47
+ end
48
+ end
49
+
50
+ def stream_without_mapping filename
51
+ if @http_chunks
52
+ @connection.send_data "#{@size.to_s(16)}\r\n"
53
+ @connection.send_file_data filename
54
+ @connection.send_data "\r\n0\r\n\r\n"
55
+ else
56
+ @connection.send_file_data filename
57
+ end
58
+ succeed
59
+ end
60
+ private :stream_without_mapping
61
+
62
+ def stream_with_mapping filename
63
+ ensure_mapping_extension_is_present
64
+
65
+ @position = 0
66
+ @mapping = EventMachine::FastFileReader::Mapper.new filename
67
+ stream_one_chunk
68
+ end
69
+ private :stream_with_mapping
70
+
71
+ def stream_one_chunk
72
+ loop {
73
+ if @position < @size
74
+ if @connection.get_outbound_data_size > BackpressureLevel
75
+ EventMachine::next_tick {stream_one_chunk}
76
+ break
77
+ else
78
+ len = @size - @position
79
+ len = ChunkSize if (len > ChunkSize)
80
+
81
+ @connection.send_data( "#{len.to_s(16)}\r\n" ) if @http_chunks
82
+ @connection.send_data( @mapping.get_chunk( @position, len ))
83
+ @connection.send_data("\r\n") if @http_chunks
84
+
85
+ @position += len
86
+ end
87
+ else
88
+ @connection.send_data "0\r\n\r\n" if @http_chunks
89
+ @mapping.close
90
+ succeed
91
+ break
92
+ end
93
+ }
94
+ end
95
+
96
+ #--
97
+ # We use an outboard extension class to get memory-mapped files.
98
+ # It's outboard to avoid polluting the core distro, but that means
99
+ # there's a "hidden" dependency on it. The first time we get here in
100
+ # any run, try to load up the dependency extension. User code will see
101
+ # a LoadError if it's not available, but code that doesn't require
102
+ # mapped files will work fine without it. This is a somewhat difficult
103
+ # compromise between usability and proper modularization.
104
+ #
105
+ def ensure_mapping_extension_is_present
106
+ @@fastfilereader ||= (require 'fastfilereaderext')
107
+ end
108
+ private :ensure_mapping_extension_is_present
109
+
110
+ end
111
+ end
112
+
@@ -0,0 +1,1756 @@
1
+ # $Id$
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
+ =begin
45
+ $eventmachine_library ||= nil
46
+ case $eventmachine_library
47
+ when :pure_ruby
48
+ require 'pr_eventmachine'
49
+ when :extension
50
+ require 'rubyeventmachine'
51
+ else
52
+ # This is the case that most user code will take.
53
+ # Prefer the extension if available.
54
+ begin
55
+ require 'rubyeventmachine'
56
+ rescue LoadError
57
+ require 'pr_eventmachine'
58
+ end
59
+ end
60
+ =end
61
+
62
+
63
+ if RUBY_PLATFORM =~ /java/
64
+ require 'java'
65
+ require 'jeventmachine'
66
+ else
67
+ if $eventmachine_library == :pure_ruby or ENV['EVENTMACHINE_LIBRARY'] == "pure_ruby"
68
+ require 'pr_eventmachine'
69
+ else
70
+ require 'rubyeventmachine'
71
+ end
72
+ end
73
+
74
+
75
+ require "eventmachine_version"
76
+ require 'em/deferrable'
77
+ require 'em/future'
78
+ require 'em/eventable'
79
+ require 'em/messages'
80
+ require 'em/streamer'
81
+ require 'em/spawnable'
82
+
83
+ require 'shellwords'
84
+
85
+ #-- Additional requires are at the BOTTOM of this file, because they
86
+ #-- depend on stuff defined in here. Refactor that someday.
87
+
88
+
89
+
90
+ # == Introduction
91
+ # EventMachine provides a fast, lightweight framework for implementing
92
+ # Ruby programs that can use the network to communicate with other
93
+ # processes. Using EventMachine, Ruby programmers can easily connect
94
+ # to remote servers and act as servers themselves. EventMachine does not
95
+ # supplant the Ruby IP libraries. It does provide an alternate technique
96
+ # for those applications requiring better performance, scalability,
97
+ # and discipline over the behavior of network sockets, than is easily
98
+ # obtainable using the built-in libraries, especially in applications
99
+ # which are structurally well-suited for the event-driven programming model.
100
+ #
101
+ # EventMachine provides a perpetual event-loop which your programs can
102
+ # start and stop. Within the event loop, TCP network connections are
103
+ # initiated and accepted, based on EventMachine methods called by your
104
+ # program. You also define callback methods which are called by EventMachine
105
+ # when events of interest occur within the event-loop.
106
+ #
107
+ # User programs will be called back when the following events occur:
108
+ # * When the event loop accepts network connections from remote peers
109
+ # * When data is received from network connections
110
+ # * When connections are closed, either by the local or the remote side
111
+ # * When user-defined timers expire
112
+ #
113
+ # == Usage example
114
+ #
115
+ # Here's a fully-functional echo server implemented in EventMachine:
116
+ #
117
+ # require 'rubygems'
118
+ # require 'eventmachine'
119
+ #
120
+ # module EchoServer
121
+ # def receive_data data
122
+ # send_data ">>>you sent: #{data}"
123
+ # close_connection if data =~ /quit/i
124
+ # end
125
+ # end
126
+ #
127
+ # EventMachine::run {
128
+ # EventMachine::start_server "192.168.0.100", 8081, EchoServer
129
+ # }
130
+ #
131
+ # What's going on here? Well, we have defined the module EchoServer to
132
+ # implement the semantics of the echo protocol (more about that shortly).
133
+ # The last three lines invoke the event-machine itself, which runs forever
134
+ # unless one of your callbacks terminates it. The block that you supply
135
+ # to EventMachine::run contains code that runs immediately after the event
136
+ # machine is initialized and before it starts looping. This is the place
137
+ # to open up a TCP server by specifying the address and port it will listen
138
+ # on, together with the module that will process the data.
139
+ #
140
+ # Our EchoServer is extremely simple as the echo protocol doesn't require
141
+ # much work. Basically you want to send back to the remote peer whatever
142
+ # data it sends you. We'll dress it up with a little extra text to make it
143
+ # interesting. Also, we'll close the connection in case the received data
144
+ # contains the word "quit."
145
+ #
146
+ # So what about this module EchoServer? Well, whenever a network connection
147
+ # (either a client or a server) starts up, EventMachine instantiates an anonymous
148
+ # class, that your module has been mixed into. Exactly one of these class
149
+ # instances is created for each connection. Whenever an event occurs on a
150
+ # given connection, its corresponding object automatically calls specific
151
+ # instance methods which your module may redefine. The code in your module
152
+ # always runs in the context of a class instance, so you can create instance
153
+ # variables as you wish and they will be carried over to other callbacks
154
+ # made on that same connection.
155
+ #
156
+ # Looking back up at EchoServer, you can see that we've defined the method
157
+ # receive_data which (big surprise) is called whenever data has been received
158
+ # from the remote end of the connection. Very simple. We get the data
159
+ # (a String object) and can do whatever we wish with it. In this case,
160
+ # we use the method send_data to return the received data to the caller,
161
+ # with some extra text added in. And if the user sends the word "quit,"
162
+ # we'll close the connection with (naturally) close_connection.
163
+ # (Notice that closing the connection doesn't terminate the processing loop,
164
+ # or change the fact that your echo server is still accepting connections!)
165
+ #
166
+ #
167
+ # == Questions and Futures
168
+ # Would it be useful for EventMachine to incorporate the Observer pattern
169
+ # and make use of the corresponding Ruby <tt>observer</tt> package?
170
+ # Interesting thought.
171
+ #
172
+ #
173
+ module EventMachine
174
+ class FileNotFound < Exception; end
175
+
176
+ # EventMachine::run initializes and runs an event loop.
177
+ # This method only returns if user-callback code calls stop_event_loop.
178
+ # Use the supplied block to define your clients and servers.
179
+ # The block is called by EventMachine::run immediately after initializing
180
+ # its internal event loop but <i>before</i> running the loop.
181
+ # Therefore this block is the right place to call start_server if you
182
+ # want to accept connections from remote clients.
183
+ #
184
+ # For programs that are structured as servers, it's usually appropriate
185
+ # to start an event loop by calling EventMachine::run, and let it
186
+ # run forever. It's also possible to use EventMachine::run to make a single
187
+ # client-connection to a remote server, process the data flow from that
188
+ # single connection, and then call stop_event_loop to force EventMachine::run
189
+ # to return. Your program will then continue from the point immediately
190
+ # following the call to EventMachine::run.
191
+ #
192
+ # You can of course do both client and servers simultaneously in the same program.
193
+ # One of the strengths of the event-driven programming model is that the
194
+ # handling of network events on many different connections will be interleaved,
195
+ # and scheduled according to the actual events themselves. This maximizes
196
+ # efficiency.
197
+ #
198
+ # === Server usage example
199
+ #
200
+ # See the text at the top of this file for an example of an echo server.
201
+ #
202
+ # === Client usage example
203
+ #
204
+ # See the description of stop_event_loop for an extremely simple client example.
205
+ #
206
+ #--
207
+ # Obsoleted the use_threads mechanism.
208
+ # 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
209
+ # gets called even if an exception gets thrown within any of the user code
210
+ # that the event loop runs. The best way to see this is to run a unit
211
+ # test with two functions, each of which calls EventMachine#run and each of
212
+ # which throws something inside of #run. Without the ensure, the second test
213
+ # will start without release_machine being called and will immediately throw
214
+ # a C++ runtime error.
215
+ #
216
+ def EventMachine::run blk=nil, tail=nil, &block
217
+ @tails ||= []
218
+ tail and @tails.unshift(tail)
219
+
220
+ if reactor_running?
221
+ (b = blk || block) and b.call # next_tick(b)
222
+ else
223
+ @conns = {}
224
+ @acceptors = {}
225
+ @timers = {}
226
+ @wrapped_exception = nil
227
+ begin
228
+ @reactor_running = true
229
+ initialize_event_machine
230
+ (b = blk || block) and add_timer(0, b)
231
+ run_machine
232
+ ensure
233
+ release_machine
234
+ @reactor_running = false
235
+ end
236
+
237
+ until @tails.empty?
238
+ @tails.pop.call
239
+ end
240
+
241
+ raise @wrapped_exception if @wrapped_exception
242
+ end
243
+ end
244
+
245
+
246
+ # Sugars a common use case. Will pass the given block to #run, but will terminate
247
+ # the reactor loop and exit the function as soon as the code in the block completes.
248
+ # (Normally, #run keeps running indefinitely, even after the block supplied to it
249
+ # finishes running, until user code calls #stop.)
250
+ #
251
+ def EventMachine::run_block &block
252
+ pr = proc {
253
+ block.call
254
+ EventMachine::stop
255
+ }
256
+ run(&pr)
257
+ end
258
+
259
+ # fork_reactor forks a new process and calls EM#run inside of it, passing your block.
260
+ #--
261
+ # This implementation is subject to change, especially if we clean up the relationship
262
+ # of EM#run to @reactor_running.
263
+ # Original patch by Aman Gupta.
264
+ #
265
+ def EventMachine::fork_reactor &block
266
+ Kernel.fork do
267
+ if self.reactor_running?
268
+ self.stop_event_loop
269
+ self.release_machine
270
+ self.instance_variable_set( '@reactor_running', false )
271
+ end
272
+ self.run block
273
+ end
274
+ end
275
+
276
+
277
+ # +deprecated+
278
+ #--
279
+ # EventMachine#run_without_threads is semantically identical
280
+ # to EventMachine#run, but it runs somewhat faster.
281
+ # However, it must not be used in applications that spin
282
+ # Ruby threads.
283
+ def EventMachine::run_without_threads &block
284
+ #EventMachine::run false, &block
285
+ EventMachine::run(&block)
286
+ end
287
+
288
+ # EventMachine#add_timer adds a one-shot timer to the event loop.
289
+ # Call it with one or two parameters. The first parameters is a delay-time
290
+ # expressed in <i>seconds</i> (not milliseconds). The second parameter, if
291
+ # present, must be a proc object. If a proc object is not given, then you
292
+ # can also simply pass a block to the method call.
293
+ #
294
+ # EventMachine#add_timer may be called from the block passed to EventMachine#run
295
+ # or from any callback method. It schedules execution of the proc or block
296
+ # passed to add_timer, after the passage of an interval of time equal to
297
+ # <i>at least</i> the number of seconds specified in the first parameter to
298
+ # the call.
299
+ #
300
+ # EventMachine#add_timer is a <i>non-blocking</i> call. Callbacks can and will
301
+ # be called during the interval of time that the timer is in effect.
302
+ # There is no built-in limit to the number of timers that can be outstanding at
303
+ # any given time.
304
+ #
305
+ # === Usage example
306
+ #
307
+ # This example shows how easy timers are to use. Observe that two timers are
308
+ # initiated simultaneously. Also, notice that the event loop will continue
309
+ # to run even after the second timer event is processed, since there was
310
+ # no call to EventMachine#stop_event_loop. There will be no activity, of
311
+ # course, since no network clients or servers are defined. Stop the program
312
+ # with Ctrl-C.
313
+ #
314
+ # require 'rubygems'
315
+ # require 'eventmachine'
316
+ #
317
+ # EventMachine::run {
318
+ # puts "Starting the run now: #{Time.now}"
319
+ # EventMachine::add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
320
+ # EventMachine::add_timer( 10 ) { puts "Executing timer event: #{Time.now}" }
321
+ # }
322
+ #
323
+ #
324
+ #--
325
+ # Changed 04Oct06: We now pass the interval as an integer number of milliseconds.
326
+ #
327
+ def EventMachine::add_timer *args, &block
328
+ interval = args.shift
329
+ code = args.shift || block
330
+ if code
331
+ # check too many timers!
332
+ s = add_oneshot_timer((interval * 1000).to_i)
333
+ @timers[s] = code
334
+ s
335
+ end
336
+ end
337
+
338
+ # EventMachine#add_periodic_timer adds a periodic timer to the event loop.
339
+ # It takes the same parameters as the one-shot timer method, EventMachine#add_timer.
340
+ # This method schedules execution of the given block repeatedly, at intervals
341
+ # of time <i>at least</i> as great as the number of seconds given in the first
342
+ # parameter to the call.
343
+ #
344
+ # === Usage example
345
+ #
346
+ # The following sample program will write a dollar-sign to stderr every five seconds.
347
+ # (Of course if the program defined network clients and/or servers, they would
348
+ # be doing their work while the periodic timer is counting off.)
349
+ #
350
+ # EventMachine::run {
351
+ # EventMachine::add_periodic_timer( 5 ) { $stderr.write "$" }
352
+ # }
353
+ #
354
+ def EventMachine::add_periodic_timer *args, &block
355
+ interval = args.shift
356
+ code = args.shift || block
357
+ if code
358
+ block_1 = proc {
359
+ code.call
360
+ EventMachine::add_periodic_timer interval, code
361
+ }
362
+ add_timer interval, block_1
363
+ end
364
+ end
365
+
366
+ #--
367
+ #
368
+ def EventMachine::cancel_timer signature
369
+ @timers[signature] = proc{} if @timers.has_key?(signature)
370
+ end
371
+ private_class_method :cancel_timer
372
+
373
+
374
+ # stop_event_loop may called from within a callback method
375
+ # while EventMachine's processing loop is running.
376
+ # It causes the processing loop to stop executing, which
377
+ # will cause all open connections and accepting servers
378
+ # to be run down and closed. <i>Callbacks for connection-termination
379
+ # will be called</i> as part of the processing of stop_event_loop.
380
+ # (There currently is no option to panic-stop the loop without
381
+ # closing connections.) When all of this processing is complete,
382
+ # the call to EventMachine::run which started the processing loop
383
+ # will return and program flow will resume from the statement
384
+ # following EventMachine::run call.
385
+ #
386
+ # === Usage example
387
+ #
388
+ # require 'rubygems'
389
+ # require 'eventmachine'
390
+ #
391
+ # module Redmond
392
+ #
393
+ # def post_init
394
+ # puts "We're sending a dumb HTTP request to the remote peer."
395
+ # send_data "GET / HTTP/1.1\r\nHost: www.microsoft.com\r\n\r\n"
396
+ # end
397
+ #
398
+ # def receive_data data
399
+ # puts "We received #{data.length} bytes from the remote peer."
400
+ # puts "We're going to stop the event loop now."
401
+ # EventMachine::stop_event_loop
402
+ # end
403
+ #
404
+ # def unbind
405
+ # puts "A connection has terminated."
406
+ # end
407
+ #
408
+ # end
409
+ #
410
+ # puts "We're starting the event loop now."
411
+ # EventMachine::run {
412
+ # EventMachine::connect "www.microsoft.com", 80, Redmond
413
+ # }
414
+ # puts "The event loop has stopped."
415
+ #
416
+ # This program will produce approximately the following output:
417
+ #
418
+ # We're starting the event loop now.
419
+ # We're sending a dumb HTTP request to the remote peer.
420
+ # We received 1440 bytes from the remote peer.
421
+ # We're going to stop the event loop now.
422
+ # A connection has terminated.
423
+ # The event loop has stopped.
424
+ #
425
+ #
426
+ def EventMachine::stop_event_loop
427
+ EventMachine::stop
428
+ end
429
+
430
+ # EventMachine::start_server initiates a TCP server (socket
431
+ # acceptor) on the specified IP address and port.
432
+ # The IP address must be valid on the machine where the program
433
+ # runs, and the process must be privileged enough to listen
434
+ # on the specified port (on Unix-like systems, superuser privileges
435
+ # are usually required to listen on any port lower than 1024).
436
+ # Only one listener may be running on any given address/port
437
+ # combination. start_server will fail if the given address and port
438
+ # are already listening on the machine, either because of a prior call
439
+ # to start_server or some unrelated process running on the machine.
440
+ # If start_server succeeds, the new network listener becomes active
441
+ # immediately and starts accepting connections from remote peers,
442
+ # and these connections generate callback events that are processed
443
+ # by the code specified in the handler parameter to start_server.
444
+ #
445
+ # The optional handler which is passed to start_server is the key
446
+ # to EventMachine's ability to handle particular network protocols.
447
+ # The handler parameter passed to start_server must be a Ruby Module
448
+ # that you must define. When the network server that is started by
449
+ # start_server accepts a new connection, it instantiates a new
450
+ # object of an anonymous class that is inherited from EventMachine::Connection,
451
+ # <i>into which the methods from your handler have been mixed.</i>
452
+ # Your handler module may redefine any of the methods in EventMachine::Connection
453
+ # in order to implement the specific behavior of the network protocol.
454
+ #
455
+ # Callbacks invoked in response to network events <i>always</i> take place
456
+ # within the execution context of the object derived from EventMachine::Connection
457
+ # extended by your handler module. There is one object per connection, and
458
+ # all of the callbacks invoked for a particular connection take the form
459
+ # of instance methods called against the corresponding EventMachine::Connection
460
+ # object. Therefore, you are free to define whatever instance variables you
461
+ # wish, in order to contain the per-connection state required by the network protocol you are
462
+ # implementing.
463
+ #
464
+ # start_server is often called inside the block passed to EventMachine::run,
465
+ # but it can be called from any EventMachine callback. start_server will fail
466
+ # unless the EventMachine event loop is currently running (which is why
467
+ # it's often called in the block suppled to EventMachine::run).
468
+ #
469
+ # You may call start_server any number of times to start up network
470
+ # listeners on different address/port combinations. The servers will
471
+ # all run simultaneously. More interestingly, each individual call to start_server
472
+ # can specify a different handler module and thus implement a different
473
+ # network protocol from all the others.
474
+ #
475
+ # === Usage example
476
+ # Here is an example of a server that counts lines of input from the remote
477
+ # peer and sends back the total number of lines received, after each line.
478
+ # Try the example with more than one client connection opened via telnet,
479
+ # and you will see that the line count increments independently on each
480
+ # of the client connections. Also very important to note, is that the
481
+ # handler for the receive_data function, which our handler redefines, may
482
+ # not assume that the data it receives observes any kind of message boundaries.
483
+ # Also, to use this example, be sure to change the server and port parameters
484
+ # to the start_server call to values appropriate for your environment.
485
+ #
486
+ # require 'rubygems'
487
+ # require 'eventmachine'
488
+ #
489
+ # module LineCounter
490
+ #
491
+ # MaxLinesPerConnection = 10
492
+ #
493
+ # def post_init
494
+ # puts "Received a new connection"
495
+ # @data_received = ""
496
+ # @line_count = 0
497
+ # end
498
+ #
499
+ # def receive_data data
500
+ # @data_received << data
501
+ # while @data_received.slice!( /^[^\n]*[\n]/m )
502
+ # @line_count += 1
503
+ # send_data "received #{@line_count} lines so far\r\n"
504
+ # @line_count == MaxLinesPerConnection and close_connection_after_writing
505
+ # end
506
+ # end
507
+ #
508
+ # end # module LineCounter
509
+ #
510
+ # EventMachine::run {
511
+ # host,port = "192.168.0.100", 8090
512
+ # EventMachine::start_server host, port, LineCounter
513
+ # puts "Now accepting connections on address #{host}, port #{port}..."
514
+ # EventMachine::add_periodic_timer( 10 ) { $stderr.write "*" }
515
+ # }
516
+ #
517
+ #
518
+ def EventMachine::start_server server, port, handler=nil, *args, &block
519
+ klass = if (handler and handler.is_a?(Class))
520
+ handler
521
+ else
522
+ Class.new( Connection ) {handler and include handler}
523
+ end
524
+
525
+ arity = klass.instance_method(:initialize).arity
526
+ expected = arity >= 0 ? arity : -(arity + 1)
527
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
528
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
529
+ end
530
+
531
+ s = start_tcp_server server, port
532
+ @acceptors[s] = [klass,args,block]
533
+ s
534
+ end
535
+
536
+
537
+ # Stop a TCP server socket that was started with EventMachine#start_server.
538
+ #--
539
+ # Requested by Kirk Haines. TODO, this isn't OOP enough. We ought somehow
540
+ # to have #start_server return an object that has a close or a stop method on it.
541
+ #
542
+ def EventMachine::stop_server signature
543
+ EventMachine::stop_tcp_server signature
544
+ end
545
+
546
+ def EventMachine::start_unix_domain_server filename, handler=nil, *args, &block
547
+ klass = if (handler and handler.is_a?(Class))
548
+ handler
549
+ else
550
+ Class.new( Connection ) {handler and include handler}
551
+ end
552
+
553
+ arity = klass.instance_method(:initialize).arity
554
+ expected = arity >= 0 ? arity : -(arity + 1)
555
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
556
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
557
+ end
558
+
559
+ s = start_unix_server filename
560
+ @acceptors[s] = [klass,args,block]
561
+ s
562
+ end
563
+
564
+ # EventMachine#connect initiates a TCP connection to a remote
565
+ # server and sets up event-handling for the connection.
566
+ # You can call EventMachine#connect in the block supplied
567
+ # to EventMachine#run or in any callback method.
568
+ #
569
+ # EventMachine#connect takes the IP address (or hostname) and
570
+ # port of the remote server you want to connect to.
571
+ # It also takes an optional handler Module which you must define, that
572
+ # contains the callbacks that will be invoked by the event loop
573
+ # on behalf of the connection.
574
+ #
575
+ # See the description of EventMachine#start_server for a discussion
576
+ # of the handler Module. All of the details given in that description
577
+ # apply for connections created with EventMachine#connect.
578
+ #
579
+ # === Usage Example
580
+ #
581
+ # Here's a program which connects to a web server, sends a naive
582
+ # request, parses the HTTP header of the response, and then
583
+ # (antisocially) ends the event loop, which automatically drops the connection
584
+ # (and incidentally calls the connection's unbind method).
585
+ #
586
+ # require 'rubygems'
587
+ # require 'eventmachine'
588
+ #
589
+ # module DumbHttpClient
590
+ #
591
+ # def post_init
592
+ # send_data "GET / HTTP/1.1\r\nHost: _\r\n\r\n"
593
+ # @data = ""
594
+ # end
595
+ #
596
+ # def receive_data data
597
+ # @data << data
598
+ # if @data =~ /[\n][\r]*[\n]/m
599
+ # puts "RECEIVED HTTP HEADER:"
600
+ # $`.each {|line| puts ">>> #{line}" }
601
+ #
602
+ # puts "Now we'll terminate the loop, which will also close the connection"
603
+ # EventMachine::stop_event_loop
604
+ # end
605
+ # end
606
+ #
607
+ # def unbind
608
+ # puts "A connection has terminated"
609
+ # end
610
+ #
611
+ # end # DumbHttpClient
612
+ #
613
+ #
614
+ # EventMachine::run {
615
+ # EventMachine::connect "www.bayshorenetworks.com", 80, DumbHttpClient
616
+ # }
617
+ # puts "The event loop has ended"
618
+ #
619
+ #
620
+ # There are times when it's more convenient to define a protocol handler
621
+ # as a Class rather than a Module. Here's how to do this:
622
+ #
623
+ # class MyProtocolHandler < EventMachine::Connection
624
+ # def initialize *args
625
+ # super
626
+ # # whatever else you want to do here
627
+ # end
628
+ #
629
+ # #.......your other class code
630
+ # end # class MyProtocolHandler
631
+ #
632
+ # If you do this, then an instance of your class will be instantiated to handle
633
+ # every network connection created by your code or accepted by servers that you
634
+ # create. If you redefine #post_init in your protocol-handler class, your
635
+ # #post_init method will be called _inside_ the call to #super that you will
636
+ # make in your #initialize method (if you provide one).
637
+ #
638
+ #--
639
+ # EventMachine::connect initiates a TCP connection to a remote
640
+ # server and sets up event-handling for the connection.
641
+ # It internally creates an object that should not be handled
642
+ # by the caller. HOWEVER, it's often convenient to get the
643
+ # object to set up interfacing to other objects in the system.
644
+ # We return the newly-created anonymous-class object to the caller.
645
+ # It's expected that a considerable amount of code will depend
646
+ # on this behavior, so don't change it.
647
+ #
648
+ # Ok, added support for a user-defined block, 13Apr06.
649
+ # This leads us to an interesting choice because of the
650
+ # presence of the post_init call, which happens in the
651
+ # initialize method of the new object. We call the user's
652
+ # block and pass the new object to it. This is a great
653
+ # way to do protocol-specific initiation. It happens
654
+ # AFTER post_init has been called on the object, which I
655
+ # certainly hope is the right choice.
656
+ # Don't change this lightly, because accepted connections
657
+ # are different from connected ones and we don't want
658
+ # to have them behave differently with respect to post_init
659
+ # if at all possible.
660
+ #
661
+ def EventMachine::connect server, port, handler=nil, *args
662
+ klass = if (handler and handler.is_a?(Class))
663
+ handler
664
+ else
665
+ Class.new( Connection ) {handler and include handler}
666
+ end
667
+
668
+ arity = klass.instance_method(:initialize).arity
669
+ expected = arity >= 0 ? arity : -(arity + 1)
670
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
671
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
672
+ end
673
+
674
+ s = connect_server server, port
675
+ c = klass.new s, *args
676
+ @conns[s] = c
677
+ block_given? and yield c
678
+ c
679
+ end
680
+
681
+ # EventMachine::attach registers a given file descriptor or IO object with the eventloop
682
+ #
683
+ # If the handler provided has the functions notify_readable or notify_writable defined,
684
+ # EventMachine will not read or write from the socket, and instead fire the corresponding
685
+ # callback on the handler.
686
+ #
687
+ # To detach the file descriptor, use EventMachine::Connection#detach
688
+ #
689
+ # === Usage Example
690
+ #
691
+ # module SimpleHttpClient
692
+ # def initialize sock
693
+ # @sock = sock
694
+ # end
695
+ #
696
+ # def notify_readable
697
+ # header = @sock.readline
698
+ #
699
+ # if header == "\r\n"
700
+ # # detach returns the file descriptor number (fd == @sock.fileno)
701
+ # fd = detach
702
+ # end
703
+ # rescue EOFError
704
+ # detach
705
+ # end
706
+ #
707
+ # def unbind
708
+ # EM.next_tick do
709
+ # # socket is detached from the eventloop, but still open
710
+ # data = @sock.read
711
+ # end
712
+ # end
713
+ # end
714
+ #
715
+ # EM.run{
716
+ # $sock = TCPSocket.new('site.com', 80)
717
+ # $sock.write("GET / HTTP/1.0\r\n\r\n")
718
+ # EM.attach $sock, SimpleHttpClient, $sock
719
+ # }
720
+ #
721
+ #--
722
+ # Thanks to Riham Aldakkak (eSpace Technologies) for the initial patch
723
+ def EventMachine::attach io, handler=nil, *args
724
+ klass = if (handler and handler.is_a?(Class))
725
+ handler
726
+ else
727
+ Class.new( Connection ) {handler and include handler}
728
+ end
729
+
730
+ arity = klass.instance_method(:initialize).arity
731
+ expected = arity >= 0 ? arity : -(arity + 1)
732
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
733
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
734
+ end
735
+
736
+ readmode = klass.public_instance_methods.any?{|m| m.to_sym == :notify_readable }
737
+ writemode = klass.public_instance_methods.any?{|m| m.to_sym == :notify_writable }
738
+
739
+ s = attach_fd io.respond_to?(:fileno) ? io.fileno : io, readmode, writemode
740
+
741
+ c = klass.new s, *args
742
+ @conns[s] = c
743
+ block_given? and yield c
744
+ c
745
+ end
746
+
747
+ #--
748
+ # EXPERIMENTAL. DO NOT RELY ON THIS METHOD TO BE HERE IN THIS FORM, OR AT ALL.
749
+ # (03Nov06)
750
+ # Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
751
+ # because we haven't set up the connection in @conns by that point.
752
+ # RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
753
+ #
754
+ # Changed 22Nov06: if called on an already-connected handler, just return the
755
+ # handler and do nothing more. Originally this condition raised an exception.
756
+ # We may want to change it yet again and call the block, if any.
757
+ #
758
+ def EventMachine::reconnect server, port, handler
759
+ raise "invalid handler" unless handler.respond_to?(:connection_completed)
760
+ #raise "still connected" if @conns.has_key?(handler.signature)
761
+ return handler if @conns.has_key?(handler.signature)
762
+ s = connect_server server, port
763
+ handler.signature = s
764
+ @conns[s] = handler
765
+ block_given? and yield handler
766
+ handler
767
+ end
768
+
769
+
770
+
771
+
772
+ # Make a connection to a Unix-domain socket. This is not implemented on Windows platforms.
773
+ # The parameter socketname is a String which identifies the Unix-domain socket you want
774
+ # to connect to. socketname is the name of a file on your local system, and in most cases
775
+ # is a fully-qualified path name. Make sure that your process has enough local permissions
776
+ # to open the Unix-domain socket.
777
+ # See also the documentation for #connect_server. This method behaves like #connect_server
778
+ # in all respects except for the fact that it connects to a local Unix-domain
779
+ # socket rather than a TCP socket.
780
+ # NOTE: this functionality will soon be subsumed into the #connect method. This method
781
+ # will still be supported as an alias.
782
+ #--
783
+ # For making connections to Unix-domain sockets.
784
+ # Eventually this has to get properly documented and unified with the TCP-connect methods.
785
+ # Note how nearly identical this is to EventMachine#connect
786
+ def EventMachine::connect_unix_domain socketname, handler=nil, *args
787
+ klass = if (handler and handler.is_a?(Class))
788
+ handler
789
+ else
790
+ Class.new( Connection ) {handler and include handler}
791
+ end
792
+
793
+ arity = klass.instance_method(:initialize).arity
794
+ expected = arity >= 0 ? arity : -(arity + 1)
795
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
796
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
797
+ end
798
+
799
+ s = connect_unix_server socketname
800
+ c = klass.new s, *args
801
+ @conns[s] = c
802
+ block_given? and yield c
803
+ c
804
+ end
805
+
806
+
807
+ # EventMachine#open_datagram_socket is for support of UDP-based
808
+ # protocols. Its usage is similar to that of EventMachine#start_server.
809
+ # It takes three parameters: an IP address (which must be valid
810
+ # on the machine which executes the method), a port number,
811
+ # and an optional Module name which will handle the data.
812
+ # This method will create a new UDP (datagram) socket and
813
+ # bind it to the address and port that you specify.
814
+ # The normal callbacks (see EventMachine#start_server) will
815
+ # be called as events of interest occur on the newly-created
816
+ # socket, but there are some differences in how they behave.
817
+ #
818
+ # Connection#receive_data will be called when a datagram packet
819
+ # is received on the socket, but unlike TCP sockets, the message
820
+ # boundaries of the received data will be respected. In other words,
821
+ # if the remote peer sent you a datagram of a particular size,
822
+ # you may rely on Connection#receive_data to give you the
823
+ # exact data in the packet, with the original data length.
824
+ # Also observe that Connection#receive_data may be called with a
825
+ # <i>zero-length</i> data payload, since empty datagrams are permitted
826
+ # in UDP.
827
+ #
828
+ # Connection#send_data is available with UDP packets as with TCP,
829
+ # but there is an important difference. Because UDP communications
830
+ # are <i>connectionless,</i> there is no implicit recipient for the packets you
831
+ # send. Ordinarily you must specify the recipient for each packet you send.
832
+ # However, EventMachine
833
+ # provides for the typical pattern of receiving a UDP datagram
834
+ # from a remote peer, performing some operation, and then sending
835
+ # one or more packets in response to the same remote peer.
836
+ # To support this model easily, just use Connection#send_data
837
+ # in the code that you supply for Connection:receive_data.
838
+ # EventMachine will
839
+ # provide an implicit return address for any messages sent to
840
+ # Connection#send_data within the context of a Connection#receive_data callback,
841
+ # and your response will automatically go to the correct remote peer.
842
+ # (TODO: Example-code needed!)
843
+ #
844
+ # Observe that the port number that you supply to EventMachine#open_datagram_socket
845
+ # may be zero. In this case, EventMachine will create a UDP socket
846
+ # that is bound to an <i>ephemeral</i> (not well-known) port.
847
+ # This is not appropriate for servers that must publish a well-known
848
+ # port to which remote peers may send datagrams. But it can be useful
849
+ # for clients that send datagrams to other servers.
850
+ # If you do this, you will receive any responses from the remote
851
+ # servers through the normal Connection#receive_data callback.
852
+ # Observe that you will probably have issues with firewalls blocking
853
+ # the ephemeral port numbers, so this technique is most appropriate for LANs.
854
+ # (TODO: Need an example!)
855
+ #
856
+ # If you wish to send datagrams to arbitrary remote peers (not
857
+ # necessarily ones that have sent data to which you are responding),
858
+ # then see Connection#send_datagram.
859
+ #
860
+ # DO NOT call send_data from a datagram socket
861
+ # outside of a #receive_data method. Use #send_datagram. If you do use #send_data
862
+ # outside of a #receive_data method, you'll get a confusing error
863
+ # because there is no "peer," as #send_data requires. (Inside of #receive_data,
864
+ # #send_data "fakes" the peer as described above.)
865
+ #
866
+ #--
867
+ # Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
868
+ # out that this originally did not take a class but only a module.
869
+ #
870
+ def self::open_datagram_socket address, port, handler=nil, *args
871
+ klass = if (handler and handler.is_a?(Class))
872
+ handler
873
+ else
874
+ Class.new( Connection ) {handler and include handler}
875
+ end
876
+
877
+ arity = klass.instance_method(:initialize).arity
878
+ expected = arity >= 0 ? arity : -(arity + 1)
879
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
880
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
881
+ end
882
+
883
+ s = open_udp_socket address, port
884
+ c = klass.new s, *args
885
+ @conns[s] = c
886
+ block_given? and yield c
887
+ c
888
+ end
889
+
890
+
891
+ # For advanced users. This function sets the default timer granularity, which by default is
892
+ # slightly smaller than 100 milliseconds. Call this function to set a higher or lower granularity.
893
+ # The function affects the behavior of #add_timer and #add_periodic_timer. Most applications
894
+ # will not need to call this function.
895
+ #
896
+ # The argument is a number of milliseconds. Avoid setting the quantum to very low values because
897
+ # that may reduce performance under some extreme conditions. We recommend that you not set a quantum
898
+ # lower than 10.
899
+ #
900
+ # You may only call this function while an EventMachine loop is running (that is, after a call to
901
+ # EventMachine#run and before a subsequent call to EventMachine#stop).
902
+ #
903
+ def self::set_quantum mills
904
+ set_timer_quantum mills.to_i
905
+ end
906
+
907
+ # Sets the maximum number of timers and periodic timers that may be outstanding at any
908
+ # given time. You only need to call #set_max_timers if you need more than the default
909
+ # number of timers, which on most platforms is 1000.
910
+ # Call this method before calling EventMachine#run.
911
+ #
912
+ def self::set_max_timers ct
913
+ set_max_timer_count ct
914
+ end
915
+
916
+ #--
917
+ # The is the responder for the loopback-signalled event.
918
+ # It can be fired either by code running on a separate thread (EM#defer) or on
919
+ # the main thread (EM#next_tick).
920
+ # It will often happen that a next_tick handler will reschedule itself. We
921
+ # consume a copy of the tick queue so that tick events scheduled by tick events
922
+ # have to wait for the next pass through the reactor core.
923
+ #
924
+ def self::run_deferred_callbacks # :nodoc:
925
+ until (@resultqueue ||= []).empty?
926
+ result,cback = @resultqueue.pop
927
+ cback.call result if cback
928
+ end
929
+
930
+ @next_tick_queue ||= []
931
+ if (l = @next_tick_queue.length) > 0
932
+ l.times {|i| @next_tick_queue[i].call}
933
+ @next_tick_queue.slice!( 0...l )
934
+ end
935
+
936
+ =begin
937
+ (@next_tick_queue ||= []).length.times {
938
+ cback=@next_tick_queue.pop and cback.call
939
+ }
940
+ =end
941
+ =begin
942
+ if (@next_tick_queue ||= []) and @next_tick_queue.length > 0
943
+ ary = @next_tick_queue.dup
944
+ @next_tick_queue.clear
945
+ until ary.empty?
946
+ cback=ary.pop and cback.call
947
+ end
948
+ end
949
+ =end
950
+ end
951
+
952
+
953
+ # #defer is for integrating blocking operations into EventMachine's control flow.
954
+ # Call #defer with one or two blocks, as shown below (the second block is <i>optional</i>):
955
+ #
956
+ # operation = proc {
957
+ # # perform a long-running operation here, such as a database query.
958
+ # "result" # as usual, the last expression evaluated in the block will be the return value.
959
+ # }
960
+ # callback = proc {|result|
961
+ # # do something with result here, such as send it back to a network client.
962
+ # }
963
+ #
964
+ # EventMachine.defer( operation, callback )
965
+ #
966
+ # The action of #defer is to take the block specified in the first parameter (the "operation")
967
+ # and schedule it for asynchronous execution on an internal thread pool maintained by EventMachine.
968
+ # When the operation completes, it will pass the result computed by the block (if any)
969
+ # back to the EventMachine reactor. Then, EventMachine calls the block specified in the
970
+ # second parameter to #defer (the "callback"), as part of its normal, synchronous
971
+ # event handling loop. The result computed by the operation block is passed as a parameter
972
+ # to the callback. You may omit the callback parameter if you don't need to execute any code
973
+ # after the operation completes.
974
+ #
975
+ # <i>Caveats:</i>
976
+ # Note carefully that the code in your deferred operation will be executed on a separate
977
+ # thread from the main EventMachine processing and all other Ruby threads that may exist in
978
+ # your program. Also, multiple deferred operations may be running at once! Therefore, you
979
+ # are responsible for ensuring that your operation code is threadsafe. [Need more explanation
980
+ # and examples.]
981
+ # Don't write a deferred operation that will block forever. If so, the current implementation will
982
+ # not detect the problem, and the thread will never be returned to the pool. EventMachine limits
983
+ # the number of threads in its pool, so if you do this enough times, your subsequent deferred
984
+ # operations won't get a chance to run. [We might put in a timer to detect this problem.]
985
+ #
986
+ #--
987
+ # OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here
988
+ # without syncing there.
989
+ #
990
+ # Running with $VERBOSE set to true gives a warning unless all ivars are defined when
991
+ # they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we
992
+ # need it, because the Ruby threads are so heavyweight. We end up with this bizarre
993
+ # way of initializing @threadqueue because EventMachine is a Module, not a Class, and
994
+ # has no constructor.
995
+ #
996
+ def self::defer op, callback = nil
997
+ @need_threadqueue ||= 0
998
+ if @need_threadqueue == 0
999
+ @need_threadqueue = 1
1000
+ require 'thread'
1001
+ @threadqueue = Queue.new
1002
+ @resultqueue = Queue.new
1003
+ 20.times {|ix|
1004
+ Thread.new {
1005
+ my_ix = ix
1006
+ loop {
1007
+ op,cback = @threadqueue.pop
1008
+ result = op.call
1009
+ @resultqueue << [result, cback]
1010
+ EventMachine.signal_loopbreak
1011
+ }
1012
+ }
1013
+ }
1014
+ end
1015
+
1016
+ @threadqueue << [op,callback]
1017
+ end
1018
+
1019
+
1020
+ # Schedules a proc for execution immediately after the next "turn" through the reactor
1021
+ # core. An advanced technique, this can be useful for improving memory management and/or
1022
+ # application responsiveness, especially when scheduling large amounts of data for
1023
+ # writing to a network connection. TODO, we need a FAQ entry on this subject.
1024
+ #
1025
+ # #next_tick takes either a single argument (which must be a Proc) or a block.
1026
+ # And I'm taking suggestions for a better name for this method.
1027
+ #--
1028
+ # This works by adding to the @resultqueue that's used for #defer.
1029
+ # The general idea is that next_tick is used when we want to give the reactor a chance
1030
+ # to let other operations run, either to balance the load out more evenly, or to let
1031
+ # outbound network buffers drain, or both. So we probably do NOT want to block, and
1032
+ # we probably do NOT want to be spinning any threads. A program that uses next_tick
1033
+ # but not #defer shouldn't suffer the penalty of having Ruby threads running. They're
1034
+ # extremely expensive even if they're just sleeping.
1035
+ #
1036
+ def self::next_tick pr=nil, &block
1037
+ raise "no argument or block given" unless ((pr && pr.respond_to?(:call)) or block)
1038
+ (@next_tick_queue ||= []) << ( pr || block )
1039
+ EventMachine.signal_loopbreak
1040
+ =begin
1041
+ (@next_tick_procs ||= []) << (pr || block)
1042
+ if @next_tick_procs.length == 1
1043
+ add_timer(0) {
1044
+ @next_tick_procs.each {|t| t.call}
1045
+ @next_tick_procs.clear
1046
+ }
1047
+ end
1048
+ =end
1049
+ end
1050
+
1051
+ # A wrapper over the setuid system call. Particularly useful when opening a network
1052
+ # server on a privileged port because you can use this call to drop privileges
1053
+ # after opening the port. Also very useful after a call to #set_descriptor_table_size,
1054
+ # which generally requires that you start your process with root privileges.
1055
+ #
1056
+ # This method has no effective implementation on Windows or in the pure-Ruby
1057
+ # implementation of EventMachine.
1058
+ # Call #set_effective_user by passing it a string containing the effective name
1059
+ # of the user whose privilege-level your process should attain.
1060
+ # This method is intended for use in enforcing security requirements, consequently
1061
+ # it will throw a fatal error and end your program if it fails.
1062
+ #
1063
+ def self::set_effective_user username
1064
+ EventMachine::setuid_string username
1065
+ end
1066
+
1067
+
1068
+ # Sets the maximum number of file or socket descriptors that your process may open.
1069
+ # You can pass this method an integer specifying the new size of the descriptor table.
1070
+ # Returns the new descriptor-table size, which may be less than the number you
1071
+ # requested. If you call this method with no arguments, it will simply return
1072
+ # the current size of the descriptor table without attempting to change it.
1073
+ #
1074
+ # The new limit on open descriptors ONLY applies to sockets and other descriptors
1075
+ # that belong to EventMachine. It has NO EFFECT on the number of descriptors
1076
+ # you can create in ordinary Ruby code.
1077
+ #
1078
+ # Not available on all platforms. Increasing the number of descriptors beyond its
1079
+ # default limit usually requires superuser privileges. (See #set_effective_user
1080
+ # for a way to drop superuser privileges while your program is running.)
1081
+ #
1082
+ def self::set_descriptor_table_size n_descriptors=nil
1083
+ EventMachine::set_rlimit_nofile n_descriptors
1084
+ end
1085
+
1086
+
1087
+
1088
+ # TODO, must document popen. At this moment, it's only available on Unix.
1089
+ # This limitation is expected to go away.
1090
+ #--
1091
+ # Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
1092
+ #
1093
+ def self::popen cmd, handler=nil
1094
+ klass = if (handler and handler.is_a?(Class))
1095
+ handler
1096
+ else
1097
+ Class.new( Connection ) {handler and include handler}
1098
+ end
1099
+
1100
+ w = Shellwords::shellwords( cmd )
1101
+ w.unshift( w.first ) if w.first
1102
+ s = invoke_popen( w )
1103
+ c = klass.new s
1104
+ @conns[s] = c
1105
+ yield(c) if block_given?
1106
+ c
1107
+ end
1108
+
1109
+
1110
+ # Tells you whether the EventMachine reactor loop is currently running. Returns true or
1111
+ # false. Useful when writing libraries that want to run event-driven code, but may
1112
+ # be running in programs that are already event-driven. In such cases, if EventMachine#reactor_running?
1113
+ # returns false, your code can invoke EventMachine#run and run your application code inside
1114
+ # the block passed to that method. If EventMachine#reactor_running? returns true, just
1115
+ # execute your event-aware code.
1116
+ #
1117
+ # This method is necessary because calling EventMachine#run inside of another call to
1118
+ # EventMachine#run generates a fatal error.
1119
+ #
1120
+ def self::reactor_running?
1121
+ (@reactor_running || false)
1122
+ end
1123
+
1124
+
1125
+ # (Experimental)
1126
+ #
1127
+ #
1128
+ def EventMachine::open_keyboard handler=nil, *args
1129
+ klass = if (handler and handler.is_a?(Class))
1130
+ handler
1131
+ else
1132
+ Class.new( Connection ) {handler and include handler}
1133
+ end
1134
+
1135
+ arity = klass.instance_method(:initialize).arity
1136
+ expected = arity >= 0 ? arity : -(arity + 1)
1137
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
1138
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
1139
+ end
1140
+
1141
+ s = read_keyboard
1142
+ c = klass.new s, *args
1143
+ @conns[s] = c
1144
+ block_given? and yield c
1145
+ c
1146
+ end
1147
+
1148
+
1149
+
1150
+ private
1151
+ def EventMachine::event_callback conn_binding, opcode, data
1152
+ #
1153
+ # Changed 27Dec07: Eliminated the hookable error handling.
1154
+ # No one was using it, and it degraded performance significantly.
1155
+ # It's in original_event_callback, which is dead code.
1156
+ #
1157
+ # Changed 25Jul08: Added a partial solution to the problem of exceptions
1158
+ # raised in user-written event-handlers. If such exceptions are not caught,
1159
+ # we must cause the reactor to stop, and then re-raise the exception.
1160
+ # Otherwise, the reactor doesn't stop and it's left on the call stack.
1161
+ # This is partial because we only added it to #unbind, where it's critical
1162
+ # (to keep unbind handlers from being re-entered when a stopping reactor
1163
+ # runs down open connections). It should go on the other calls to user
1164
+ # code, but the performance impact may be too large.
1165
+ #
1166
+ if opcode == ConnectionData
1167
+ c = @conns[conn_binding] or raise ConnectionNotBound
1168
+ c.receive_data data
1169
+ elsif opcode == ConnectionUnbound
1170
+ if c = @conns.delete( conn_binding )
1171
+ begin
1172
+ c.unbind
1173
+ rescue
1174
+ @wrapped_exception = $!
1175
+ stop
1176
+ end
1177
+ elsif c = @acceptors.delete( conn_binding )
1178
+ # no-op
1179
+ else
1180
+ raise ConnectionNotBound
1181
+ end
1182
+ elsif opcode == ConnectionAccepted
1183
+ accep,args,blk = @acceptors[conn_binding]
1184
+ raise NoHandlerForAcceptedConnection unless accep
1185
+ c = accep.new data, *args
1186
+ @conns[data] = c
1187
+ blk and blk.call(c)
1188
+ c # (needed?)
1189
+ elsif opcode == TimerFired
1190
+ t = @timers.delete( data ) or raise UnknownTimerFired
1191
+ t.call
1192
+ elsif opcode == ConnectionCompleted
1193
+ c = @conns[conn_binding] or raise ConnectionNotBound
1194
+ c.connection_completed
1195
+ elsif opcode == LoopbreakSignalled
1196
+ run_deferred_callbacks
1197
+ elsif opcode == ConnectionNotifyReadable
1198
+ c = @conns[conn_binding] or raise ConnectionNotBound
1199
+ c.notify_readable
1200
+ elsif opcode == ConnectionNotifyWritable
1201
+ c = @conns[conn_binding] or raise ConnectionNotBound
1202
+ c.notify_writable
1203
+ end
1204
+ end
1205
+
1206
+ private
1207
+ def EventMachine::original_event_callback conn_binding, opcode, data
1208
+ #
1209
+ # Added 03Oct07: Any code path that invokes user-written code must
1210
+ # wrap itself in a begin/rescue for RuntimeErrors, that calls the
1211
+ # user-overridable class method #handle_runtime_error.
1212
+ #
1213
+ if opcode == ConnectionData
1214
+ c = @conns[conn_binding] or raise ConnectionNotBound
1215
+ begin
1216
+ c.receive_data data
1217
+ rescue
1218
+ EventMachine.handle_runtime_error
1219
+ end
1220
+ elsif opcode == ConnectionUnbound
1221
+ if c = @conns.delete( conn_binding )
1222
+ begin
1223
+ c.unbind
1224
+ rescue
1225
+ EventMachine.handle_runtime_error
1226
+ end
1227
+ elsif c = @acceptors.delete( conn_binding )
1228
+ # no-op
1229
+ else
1230
+ raise ConnectionNotBound
1231
+ end
1232
+ elsif opcode == ConnectionAccepted
1233
+ accep,args,blk = @acceptors[conn_binding]
1234
+ raise NoHandlerForAcceptedConnection unless accep
1235
+ c = accep.new data, *args
1236
+ @conns[data] = c
1237
+ begin
1238
+ blk and blk.call(c)
1239
+ rescue
1240
+ EventMachine.handle_runtime_error
1241
+ end
1242
+ c # (needed?)
1243
+ elsif opcode == TimerFired
1244
+ t = @timers.delete( data ) or raise UnknownTimerFired
1245
+ begin
1246
+ t.call
1247
+ rescue
1248
+ EventMachine.handle_runtime_error
1249
+ end
1250
+ elsif opcode == ConnectionCompleted
1251
+ c = @conns[conn_binding] or raise ConnectionNotBound
1252
+ begin
1253
+ c.connection_completed
1254
+ rescue
1255
+ EventMachine.handle_runtime_error
1256
+ end
1257
+ elsif opcode == LoopbreakSignalled
1258
+ begin
1259
+ run_deferred_callbacks
1260
+ rescue
1261
+ EventMachine.handle_runtime_error
1262
+ end
1263
+ end
1264
+ end
1265
+
1266
+
1267
+ # Default handler for RuntimeErrors that are raised in user code.
1268
+ # The default behavior is to re-raise the error, which ends your program.
1269
+ # To override the default behavior, re-implement this method in your code.
1270
+ # For example:
1271
+ #
1272
+ # module EventMachine
1273
+ # def self.handle_runtime_error
1274
+ # $>.puts $!
1275
+ # end
1276
+ # end
1277
+ #
1278
+ #--
1279
+ # We need to ensure that any code path which invokes user code rescues RuntimeError
1280
+ # and calls this method. The obvious place to do that is in #event_callback,
1281
+ # but, scurrilously, it turns out that we need to be finer grained that that.
1282
+ # Periodic timers, in particular, wrap their invocations of user code inside
1283
+ # procs that do other stuff we can't not do, like schedule the next invocation.
1284
+ # This is a potential non-robustness, since we need to remember to hook in the
1285
+ # error handler whenever and wherever we change how user code is invoked.
1286
+ #
1287
+ def EventMachine::handle_runtime_error
1288
+ @runtime_error_hook ? @runtime_error_hook.call : raise
1289
+ end
1290
+
1291
+ # Sets a handler for RuntimeErrors that are raised in user code.
1292
+ # Pass a block with no parameters. You can also call this method without a block,
1293
+ # which restores the default behavior (see #handle_runtime_error).
1294
+ #
1295
+ def EventMachine::set_runtime_error_hook &blk
1296
+ @runtime_error_hook = blk
1297
+ end
1298
+
1299
+ # Documentation stub
1300
+ #--
1301
+ # This is a provisional implementation of a stream-oriented file access object.
1302
+ # We also experiment with wrapping up some better exception reporting.
1303
+ class << self
1304
+ def _open_file_for_writing filename, handler=nil
1305
+ klass = if (handler and handler.is_a?(Class))
1306
+ handler
1307
+ else
1308
+ Class.new( Connection ) {handler and include handler}
1309
+ end
1310
+
1311
+ s = _write_file filename
1312
+ c = klass.new s
1313
+ @conns[s] = c
1314
+ block_given? and yield c
1315
+ c
1316
+ end
1317
+ end
1318
+
1319
+
1320
+ # EventMachine::Connection is a class that is instantiated
1321
+ # by EventMachine's processing loop whenever a new connection
1322
+ # is created. (New connections can be either initiated locally
1323
+ # to a remote server or accepted locally from a remote client.)
1324
+ # When a Connection object is instantiated, it <i>mixes in</i>
1325
+ # the functionality contained in the user-defined module
1326
+ # specified in calls to EventMachine#connect or EventMachine#start_server.
1327
+ # User-defined handler modules may redefine any or all of the standard
1328
+ # methods defined here, as well as add arbitrary additional code
1329
+ # that will also be mixed in.
1330
+ #
1331
+ # EventMachine manages one object inherited from EventMachine::Connection
1332
+ # (and containing the mixed-in user code) for every network connection
1333
+ # that is active at any given time.
1334
+ # The event loop will automatically call methods on EventMachine::Connection
1335
+ # objects whenever specific events occur on the corresponding connections,
1336
+ # as described below.
1337
+ #
1338
+ # This class is never instantiated by user code, and does not publish an
1339
+ # initialize method. The instance methods of EventMachine::Connection
1340
+ # which may be called by the event loop are: post_init, receive_data,
1341
+ # and unbind. All of the other instance methods defined here are called
1342
+ # only by user code.
1343
+ #
1344
+ class Connection
1345
+ # EXPERIMENTAL. Added the reconnect methods, which may go away.
1346
+ attr_accessor :signature
1347
+
1348
+ # Override .new so subclasses don't have to call super and can ignore
1349
+ # connection-specific arguments
1350
+ #
1351
+ def self.new sig, *args #:nodoc:
1352
+ allocate.instance_eval do
1353
+ # Call a superclass's #initialize if it has one
1354
+ initialize *args
1355
+
1356
+ # Store signature and run #post_init
1357
+ @signature = sig
1358
+ associate_callback_target sig
1359
+ post_init
1360
+
1361
+ self
1362
+ end
1363
+ end
1364
+
1365
+ # Stubbed initialize so legacy superclasses can safely call super
1366
+ #
1367
+ def initialize(*args) #:nodoc:
1368
+ end
1369
+
1370
+ # EventMachine::Connection#post_init is called by the event loop
1371
+ # immediately after the network connection has been established,
1372
+ # and before resumption of the network loop.
1373
+ # This method is generally not called by user code, but is called automatically
1374
+ # by the event loop. The base-class implementation is a no-op.
1375
+ # This is a very good place to initialize instance variables that will
1376
+ # be used throughout the lifetime of the network connection.
1377
+ #
1378
+ def post_init
1379
+ end
1380
+
1381
+ # EventMachine::Connection#receive_data is called by the event loop
1382
+ # whenever data has been received by the network connection.
1383
+ # It is never called by user code.
1384
+ # receive_data is called with a single parameter, a String containing
1385
+ # the network protocol data, which may of course be binary. You will
1386
+ # generally redefine this method to perform your own processing of the incoming data.
1387
+ #
1388
+ # Here's a key point which is essential to understanding the event-driven
1389
+ # programming model: <i>EventMachine knows absolutely nothing about the protocol
1390
+ # which your code implements.</i> You must not make any assumptions about
1391
+ # the size of the incoming data packets, or about their alignment on any
1392
+ # particular intra-message or PDU boundaries (such as line breaks).
1393
+ # receive_data can and will send you arbitrary chunks of data, with the
1394
+ # only guarantee being that the data is presented to your code in the order
1395
+ # it was collected from the network. Don't even assume that the chunks of
1396
+ # data will correspond to network packets, as EventMachine can and will coalesce
1397
+ # several incoming packets into one, to improve performance. The implication for your
1398
+ # code is that you generally will need to implement some kind of a state machine
1399
+ # in your redefined implementation of receive_data. For a better understanding
1400
+ # of this, read through the examples of specific protocol handlers given
1401
+ # elsewhere in this package. (STUB, WE MUST ADD THESE!)
1402
+ #
1403
+ # The base-class implementation of receive_data (which will be invoked if
1404
+ # you don't redefine it) simply prints the size of each incoming data packet
1405
+ # to stdout.
1406
+ #
1407
+ def receive_data data
1408
+ puts "............>>>#{data.length}"
1409
+ end
1410
+
1411
+ # EventMachine::Connection#unbind is called by the framework whenever a connection
1412
+ # (either a server or client connection) is closed. The close can occur because
1413
+ # your code intentionally closes it (see close_connection and close_connection_after_writing),
1414
+ # because the remote peer closed the connection, or because of a network error.
1415
+ # You may not assume that the network connection is still open and able to send or
1416
+ # receive data when the callback to unbind is made. This is intended only to give
1417
+ # you a chance to clean up associations your code may have made to the connection
1418
+ # object while it was open.
1419
+ #
1420
+ def unbind
1421
+ end
1422
+
1423
+ # EventMachine::Connection#close_connection is called only by user code, and never
1424
+ # by the event loop. You may call this method against a connection object in any
1425
+ # callback handler, whether or not the callback was made against the connection
1426
+ # you want to close. close_connection <i>schedules</i> the connection to be closed
1427
+ # at the next available opportunity within the event loop. You may not assume that
1428
+ # the connection is closed when close_connection returns. In particular, the framework
1429
+ # will callback the unbind method for the particular connection at a point shortly
1430
+ # after you call close_connection. You may assume that the unbind callback will
1431
+ # take place sometime after your call to close_connection completes. In other words,
1432
+ # the unbind callback will not re-enter your code "inside" of your call to close_connection.
1433
+ # However, it's not guaranteed that a future version of EventMachine will not change
1434
+ # this behavior.
1435
+ #
1436
+ # close_connection will <i>silently discard</i> any outbound data which you have
1437
+ # sent to the connection using EventMachine::Connection#send_data but which has not
1438
+ # yet been sent across the network. If you want to avoid this behavior, use
1439
+ # EventMachine::Connection#close_connection_after_writing.
1440
+ #
1441
+ def close_connection after_writing = false
1442
+ EventMachine::close_connection @signature, after_writing
1443
+ end
1444
+
1445
+ # EventMachine::Connection#detach will remove the given connection from the event loop.
1446
+ # The connection's socket remains open and its file descriptor number is returned
1447
+ def detach
1448
+ EventMachine::detach_fd @signature
1449
+ end
1450
+
1451
+ # EventMachine::Connection#close_connection_after_writing is a variant of close_connection.
1452
+ # All of the descriptive comments given for close_connection also apply to
1453
+ # close_connection_after_writing, <i>with one exception:</i> If the connection has
1454
+ # outbound data sent using send_dat but which has not yet been sent across the network,
1455
+ # close_connection_after_writing will schedule the connection to be closed <i>after</i>
1456
+ # all of the outbound data has been safely written to the remote peer.
1457
+ #
1458
+ # Depending on the amount of outgoing data and the speed of the network,
1459
+ # considerable time may elapse between your call to close_connection_after_writing
1460
+ # and the actual closing of the socket (at which time the unbind callback will be called
1461
+ # by the event loop). During this time, you <i>may not</i> call send_data to transmit
1462
+ # additional data (that is, the connection is closed for further writes). In very
1463
+ # rare cases, you may experience a receive_data callback after your call to close_connection_after_writing,
1464
+ # depending on whether incoming data was in the process of being received on the connection
1465
+ # at the moment when you called close_connection_after_writing. Your protocol handler must
1466
+ # be prepared to properly deal with such data (probably by ignoring it).
1467
+ #
1468
+ def close_connection_after_writing
1469
+ close_connection true
1470
+ end
1471
+
1472
+ # EventMachine::Connection#send_data is only called by user code, never by
1473
+ # the event loop. You call this method to send data to the remote end of the
1474
+ # network connection. send_data is called with a single String argument, which
1475
+ # may of course contain binary data. You can call send_data any number of times.
1476
+ # send_data is an instance method of an object derived from EventMachine::Connection
1477
+ # and containing your mixed-in handler code), so if you call it without qualification
1478
+ # within a callback function, the data will be sent to the same network connection
1479
+ # that generated the callback. Calling self.send_data is exactly equivalent.
1480
+ #
1481
+ # You can also call send_data to write to a connection <i>other than the one
1482
+ # whose callback you are calling send_data from.</i> This is done by recording
1483
+ # the value of the connection in any callback function (the value self), in any
1484
+ # variable visible to other callback invocations on the same or different
1485
+ # connection objects. (Need an example to make that clear.)
1486
+ #
1487
+ def send_data data
1488
+ EventMachine::send_data @signature, data, data.length
1489
+ end
1490
+
1491
+ # Returns true if the connection is in an error state, false otherwise.
1492
+ # In general, you can detect the occurrence of communication errors or unexpected
1493
+ # disconnection by the remote peer by handing the #unbind method. In some cases, however,
1494
+ # it's useful to check the status of the connection using #error? before attempting to send data.
1495
+ # This function is synchronous: it will return immediately without blocking.
1496
+ #
1497
+ #
1498
+ def error?
1499
+ EventMachine::report_connection_error_status(@signature) != 0
1500
+ end
1501
+
1502
+ # #connection_completed is called by the event loop when a remote TCP connection
1503
+ # attempt completes successfully. You can expect to get this notification after calls
1504
+ # to EventMachine#connect. Remember that EventMachine makes remote connections
1505
+ # asynchronously, just as with any other kind of network event. #connection_completed
1506
+ # is intended primarily to assist with network diagnostics. For normal protocol
1507
+ # handling, use #post_init to perform initial work on a new connection (such as
1508
+ # send an initial set of data).
1509
+ # #post_init will always be called. #connection_completed will only be called in case
1510
+ # of a successful completion. A connection-attempt which fails will receive a call
1511
+ # to #unbind after the failure.
1512
+ def connection_completed
1513
+ end
1514
+
1515
+ # Call #start_tls at any point to initiate TLS encryption on connected streams.
1516
+ # The method is smart enough to know whether it should perform a server-side
1517
+ # or a client-side handshake. An appropriate place to call #start_tls is in
1518
+ # your redefined #post_init method, or in the #connection_completed handler for
1519
+ # an outbound connection.
1520
+ #
1521
+ # #start_tls takes an optional parameter hash that allows you to specify certificate
1522
+ # and other options to be used with this Connection object. Here are the currently-supported
1523
+ # options:
1524
+ # :cert_chain_file : takes a String, which is interpreted as the name of a readable file in the
1525
+ # local filesystem. The file is expected to contain a chain of X509 certificates in
1526
+ # PEM format, with the most-resolved certificate at the top of the file, successive
1527
+ # intermediate certs in the middle, and the root (or CA) cert at the bottom.
1528
+ #
1529
+ # :private_key_file : tales a String, which is interpreted as the name of a readable file in the
1530
+ # local filesystem. The file must contain a private key in PEM format.
1531
+ #
1532
+ #--
1533
+ # TODO: support passing an encryption parameter, which can be string or Proc, to get a passphrase
1534
+ # for encrypted private keys.
1535
+ # TODO: support passing key material via raw strings or Procs that return strings instead of
1536
+ # just filenames.
1537
+ # What will get nasty is whether we have to define a location for storing this stuff as files.
1538
+ # In general, the OpenSSL interfaces for dealing with certs and keys in files are much better
1539
+ # behaved than the ones for raw chunks of memory.
1540
+ #
1541
+ def start_tls args={}
1542
+ priv_key = args[:private_key_file] || ""
1543
+ cert = args[:cert_chain_file] || ""
1544
+ unless File.exist?(priv_key)
1545
+ raise FileNotFound.new("Private Key file not found at: #{priv_key}")
1546
+ return # FIXME: should we do something else here?
1547
+ end
1548
+ unless File.exist?(cert)
1549
+ raise FileNotFound.new("Cert Chain file not found at: #{cert}")
1550
+ return # FIXME: should we do something else here?
1551
+ end
1552
+ EventMachine::set_tls_parms(
1553
+ @signature,
1554
+ priv_key,
1555
+ cert
1556
+ )
1557
+ EventMachine::start_tls @signature
1558
+ end
1559
+
1560
+
1561
+ # send_datagram is for sending UDP messages.
1562
+ # This method may be called from any Connection object that refers
1563
+ # to an open datagram socket (see EventMachine#open_datagram_socket).
1564
+ # The method sends a UDP (datagram) packet containing the data you specify,
1565
+ # to a remote peer specified by the IP address and port that you give
1566
+ # as parameters to the method.
1567
+ # Observe that you may send a zero-length packet (empty string).
1568
+ # However, you may not send an arbitrarily-large data packet because
1569
+ # your operating system will enforce a platform-specific limit on
1570
+ # the size of the outbound packet. (Your kernel
1571
+ # will respond in a platform-specific way if you send an overlarge
1572
+ # packet: some will send a truncated packet, some will complain, and
1573
+ # some will silently drop your request).
1574
+ # On LANs, it's usually OK to send datagrams up to about 4000 bytes in length,
1575
+ # but to be really safe, send messages smaller than the Ethernet-packet
1576
+ # size (typically about 1400 bytes). Some very restrictive WANs
1577
+ # will either drop or truncate packets larger than about 500 bytes.
1578
+ #--
1579
+ # Added the Integer wrapper around the port parameter per suggestion by
1580
+ # Matthieu Riou, after he passed a String and spent hours tearing his hair out.
1581
+ #
1582
+ def send_datagram data, recipient_address, recipient_port
1583
+ data = data.to_s
1584
+ EventMachine::send_datagram @signature, data, data.length, recipient_address, Integer(recipient_port)
1585
+ end
1586
+
1587
+
1588
+ # #get_peername is used with stream-connections to obtain the identity
1589
+ # of the remotely-connected peer. If a peername is available, this method
1590
+ # returns a sockaddr structure. The method returns nil if no peername is available.
1591
+ # You can use Socket#unpack_sockaddr_in and its variants to obtain the
1592
+ # values contained in the peername structure returned from #get_peername.
1593
+ def get_peername
1594
+ EventMachine::get_peername @signature
1595
+ end
1596
+
1597
+ # #get_sockname is used with stream-connections to obtain the identity
1598
+ # of the local side of the connection. If a local name is available, this method
1599
+ # returns a sockaddr structure. The method returns nil if no local name is available.
1600
+ # You can use Socket#unpack_sockaddr_in and its variants to obtain the
1601
+ # values contained in the local-name structure returned from #get_sockname.
1602
+ def get_sockname
1603
+ EventMachine::get_sockname @signature
1604
+ end
1605
+
1606
+ # Returns the PID (kernel process identifier) of a subprocess
1607
+ # associated with this Connection object. For use with EventMachine#popen
1608
+ # and similar methods. Returns nil when there is no meaningful subprocess.
1609
+ #--
1610
+ #
1611
+ def get_pid
1612
+ EventMachine::get_subprocess_pid @signature
1613
+ end
1614
+
1615
+ # Returns a subprocess exit status. Only useful for #popen. Call it in your
1616
+ # #unbind handler.
1617
+ #
1618
+ def get_status
1619
+ EventMachine::get_subprocess_status @signature
1620
+ end
1621
+
1622
+ # comm_inactivity_timeout returns the current value (in seconds) of the inactivity-timeout
1623
+ # property of network-connection and datagram-socket objects. A nonzero value
1624
+ # indicates that the connection or socket will automatically be closed if no read or write
1625
+ # activity takes place for at least that number of seconds.
1626
+ # A zero value (the default) specifies that no automatic timeout will take place.
1627
+ def comm_inactivity_timeout
1628
+ EventMachine::get_comm_inactivity_timeout @signature
1629
+ end
1630
+
1631
+ # Alias for #set_comm_inactivity_timeout.
1632
+ def comm_inactivity_timeout= value
1633
+ self.send :set_comm_inactivity_timeout, value
1634
+ end
1635
+
1636
+ # comm_inactivity_timeout= allows you to set the inactivity-timeout property for
1637
+ # a network connection or datagram socket. Specify a non-negative numeric value in seconds.
1638
+ # If the value is greater than zero, the connection or socket will automatically be closed
1639
+ # if no read or write activity takes place for at least that number of seconds.
1640
+ # Specify a value of zero to indicate that no automatic timeout should take place.
1641
+ # Zero is the default value.
1642
+ def set_comm_inactivity_timeout value
1643
+ EventMachine::set_comm_inactivity_timeout @signature, value
1644
+ end
1645
+
1646
+ #--
1647
+ # EXPERIMENTAL. DO NOT RELY ON THIS METHOD TO REMAIN SUPPORTED.
1648
+ # (03Nov06)
1649
+ def reconnect server, port
1650
+ EventMachine::reconnect server, port, self
1651
+ end
1652
+
1653
+
1654
+ # Like EventMachine::Connection#send_data, this sends data to the remote end of
1655
+ # the network connection. EventMachine::Connection@send_file_data takes a
1656
+ # filename as an argument, though, and sends the contents of the file, in one
1657
+ # chunk. Contributed by Kirk Haines.
1658
+ #
1659
+ def send_file_data filename
1660
+ EventMachine::send_file_data @signature, filename
1661
+ end
1662
+
1663
+ # Open a file on the filesystem and send it to the remote peer. This returns an
1664
+ # object of type EventMachine::Deferrable. The object's callbacks will be executed
1665
+ # on the reactor main thread when the file has been completely scheduled for
1666
+ # transmission to the remote peer. Its errbacks will be called in case of an error
1667
+ # (such as file-not-found). #stream_file_data employs various strategems to achieve
1668
+ # the fastest possible performance, balanced against minimum consumption of memory.
1669
+ #
1670
+ # You can control the behavior of #stream_file_data with the optional arguments parameter.
1671
+ # Currently-supported arguments are:
1672
+ # :http_chunks, a boolean flag which defaults false. If true, this flag streams the
1673
+ # file data in a format compatible with the HTTP chunked-transfer encoding.
1674
+ #
1675
+ # Warning: this feature has an implicit dependency on an outboard extension,
1676
+ # evma_fastfilereader. You must install this extension in order to use #stream_file_data
1677
+ # with files larger than a certain size (currently 8192 bytes).
1678
+ #
1679
+ def stream_file_data filename, args={}
1680
+ EventMachine::FileStreamer.new( self, filename, args )
1681
+ end
1682
+
1683
+
1684
+ # TODO, document this
1685
+ #
1686
+ #
1687
+ class EventMachine::PeriodicTimer
1688
+ attr_accessor :interval
1689
+ def initialize *args, &block
1690
+ @interval = args.shift
1691
+ @code = args.shift || block
1692
+ schedule
1693
+ end
1694
+ def schedule
1695
+ EventMachine::add_timer @interval, proc {self.fire}
1696
+ end
1697
+ def fire
1698
+ @code.call
1699
+ schedule unless @cancelled
1700
+ end
1701
+ def cancel
1702
+ @cancelled = true
1703
+ end
1704
+ end
1705
+
1706
+ # TODO, document this
1707
+ #
1708
+ #
1709
+ class EventMachine::Timer
1710
+ def initialize *args, &block
1711
+ @signature = EventMachine::add_timer(*args, &block)
1712
+ end
1713
+ def cancel
1714
+ EventMachine.send :cancel_timer, @signature
1715
+ end
1716
+ end
1717
+
1718
+
1719
+
1720
+
1721
+ end
1722
+
1723
+ module Protocols
1724
+ # In this module, we define standard protocol implementations.
1725
+ # They get included from separate source files.
1726
+ end
1727
+
1728
+ end # module EventMachine
1729
+
1730
+
1731
+
1732
+ # Save everyone some typing.
1733
+ EM = EventMachine
1734
+ EM::P = EventMachine::Protocols
1735
+
1736
+
1737
+ # At the bottom of this module, we load up protocol handlers that depend on some
1738
+ # of the classes defined here. Eventually we should refactor this out so it's
1739
+ # laid out in a more logical way.
1740
+ #
1741
+
1742
+ require 'protocols/tcptest'
1743
+ require 'protocols/httpclient'
1744
+ require 'protocols/line_and_text'
1745
+ require 'protocols/linetext2'
1746
+ require 'protocols/header_and_content'
1747
+ require 'protocols/httpcli2'
1748
+ require 'protocols/stomp'
1749
+ require 'protocols/smtpclient'
1750
+ require 'protocols/smtpserver'
1751
+ require 'protocols/saslauth'
1752
+ #require 'protocols/postgres' UNCOMMENT THIS LINE WHEN THE POSTGRES CODE IS READY FOR PRIME TIME.
1753
+
1754
+ require 'em/processes'
1755
+
1756
+