eventmachine 0.12.0-i386-mswin32

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