1IO::Event(3)          User Contributed Perl Documentation         IO::Event(3)
2
3
4

NAME

6       IO::Event - Tied Filehandles for Nonblocking IO with Object Callbacks
7

SYNOPSIS

9        use IO::Event;
10        use IO::Event 'emulate_Event';
11        use IO::Event 'AnyEvent';
12
13        my $ioe = IO::Event->new($filehandle);
14
15        my $ioe = IO::Event::Socket::INET->new( [ARGS] )
16
17        my $ioe = IO::Event::Socket::UNIX->new( [ARGS] )
18
19        my $timer = IO::Event->timer(
20               [after => $seconds],
21               interval => $seconds,
22               cb => CODE);
23
24        my $idler = IO::Event->idle(
25               [min => $seconds],
26               [max => $seconds],
27               [reentrant => 0],
28               cb => CODE);
29
30        IO::Event::loop();
31
32        IO::Event::unloop_all();
33

DESCRIPTION

35       IO::Event provides a object-based callback system for handling
36       nonblocking IO.  The design goal is to provide a system that just does
37       the right thing w/o the user needing to think about it much.
38
39       All APIs are kept as simple as possible yet at the same time, all
40       functionality is accesible if needed.  Simple things are easy.  Hard
41       things are possible.
42
43       Most of the time file handling syntax will work fine: "<$filehandle>"
44       and "print $filehandle 'stuff'".
45
46       IO::Event provides automatic buffering of output (with a callback to
47       throttle).  It provides automatic line-at-a-time input.
48
49       After initial setup, call "IO::Event::loop()".
50
51       IO::Event was originally written to use Event.  IO::Event still
52       defaults to using Event but it can now use AnyEvent or its own event
53       loop.
54

CHOOSING AN EVENT HANDLER

56       Until you create your first IO::Event object, you can choose which
57       underlying event handler to use.  The default is Event.  To choose an
58       event handler, use one of the following lines, import
59       "no_emulate_Event", "emulate_Event", or "AnyEvent".
60
61        use IO::Event 'no_emulate_Event'
62        use IO::Event 'emulate_Event'
63        use IO::Event 'AnyEvent'
64
65       The "no_emulate_Event" option means: use Event.  The "emulate_Event"
66       option means IO::Event should use its own event loop.
67
68       Why?
69
70       You should use AnyEvent if you want to have compatibility with other
71       event loops.  You should use "emulate_Event" if you don't need
72       compatibility with other event loops and you have missing-event bugs
73       when using Event.  You should use Event if it works for you.
74
75       The APIs are a bit different depending on which event loop you're
76       using.
77
78   Event
79       To use Event's event loop:
80
81        use IO::Event 'no_emulate_Event';
82
83       or just:
84
85        use IO::Event
86
87       IO::Event's definition for "loop()", "timer()", "idle()" and
88       "unloop_all()" all default to the Event version unless "emulate_Event"
89       or "AnyEvent" have been imported.  This allows you to easily switch
90       back and forth between Event's API and the others.
91
92   AnyEvent
93       To use AnyEvent's select loop, import "AnyEvent".
94
95        use IO::Event 'AnyEvent';
96
97       You can use AnyEvent's API directly or you can use IO::Event's emulated
98       APIs: "IO::Event::loop()", "IO::Event::unloop()", "IO::Event::timer()",
99       and "IO::Event::idle()".  These behave like Event's routines of the
100       same name but use AnyEvent underneath.
101
102       During testing, using the pure-perl event loop of AnyEvent::Impl::Perl
103       from AnyEvent version 5.271, some read events were dropped.  To work
104       around this, a synthetic read-ready event is dispatched for all
105       connected read filehandles every two seconds.  Turn this off or adjust
106       its frequency by changing $IO::Event::AnyEvent::lost_event_hack.  A
107       numeric value is the time (in seconds) between dispatching read events.
108       A false value turns off this performance-sapping hack.
109
110       AnyEvent only provides basic support for idle() events: it promises to
111       invoke them "every now and then".
112
113   "emulate_Event"
114       To use IO::Event's own select loop, import "emulate_Event".
115
116        use IO::Event 'emulate_Event';
117
118       IO::Event does not provide a complete emulation of everything that
119       Event does.  It provides the full timer API:
120
121        my $timer = IO::Event::timer( [ARGS] )
122
123       instead of
124
125        my $timer = Event::timer( [ARGS] )
126
127       However it does not provide timer events on filehandles, nor does it
128       provide events for signals, or variable accesses.
129
130       Use "IO::Event::loop()" instead of "Event::loop()".   Use
131       "IO::Event::unloop_all()" instead of "Event::unloop_all()".  Use
132       "IO::Event::idle()" instead of "Event::idle()".  It does not provide
133       any other methods or functions from Event.   If you need them, please
134       send a patch.
135

CONSTRUCTORS

137       IO::Event->new($filehandle, [ $handler, [ $options ]])
138           The basic "new" constructor takes a filehandle and returns a
139           psuedo-filehandle.  Treat the IO::Event object as a filehandle.  Do
140           not use the original filehandle without good reason (let us know if
141           you find a good reason so we can fix the problem).
142
143           The handler is the class or object where you provide callback
144           functions to handle IO events.  It defaults to the package of the
145           calling context.
146
147           If present, $options is a hash reference with the following
148           possible keys:
149
150           description  A text description of this filehandle.  Used for
151                        debugging and error messages.
152
153           read_only    Set to true if this is a read-only filehandle.  Do not
154                        accept output.
155
156           write_only   Set to true if this is a write-only filehandle.  Do
157                        not attept to read.
158
159           autoread     Set to 0 if this should not be an auto-read
160                        filehandle.
161
162       IO::Event::Socket::INET->new( [ARGS] )
163           This constructor uses IO::Socket::INET->new() to create a socket
164           using the ARGS provided.  It returns an IO::Event object.
165
166           The handler defaults as above or can be set with an additional
167           pseudo-parameter for IO::Socket::UNIX->new(): "Handler".  A
168           description for the socket can be provided with an additional
169           psuedo-parameter: "Description".
170
171       IO::Event::Socket::UNIX->new( [ARGS] )
172           This constructor uses IO::Socket::UNIX->new() to create a socket
173           using the ARGS provided.  It returns an IO::Event object.
174
175           The handler defaults as above or can be set with an additional
176           pseudo-parameter for IO::Socket::UNIX->new(): "Handler".  A
177           description for the socket can be provided with an additional
178           psuedo-parameter: "Description".
179

MANDATORY HANDLERS

181       These handler methods must be available in the handler object/class if
182       the situation in which they would be called arises.
183
184       ie_input($handler, $ioe, $input_buffer_reference)
185           Invoked when there is fresh data in the input buffer.  The input
186           can be retrieved via directly reading it from
187           $$input_buffer_reference or via "read()" from the $ioe filehandle,
188           or by using a variety of standard methods for getting data:
189
190                   <$ioe>                  like IO::Handle
191                   $ioe->get()             like Data::LineBuffer
192                   $ioe->read()            like IO::Handle
193                   $ioe->sysread()         like IO::Handle
194                   $ioe->getline()         like IO::Handle
195                   $ioe->getlines()        like IO::Handle
196                   $ioe->getsome()         see below
197                   $ioe->ungets()          like FileHandle::Unget
198
199           At end-of-file, ie_input will only be invoked once.  There may or
200           may not be data in the input buffer.
201
202       ie_connection($handler, $ioe)
203           Invoked when a listen()ing socket is ready to accept().  It should
204           call accept:
205
206                   sub ie_connection
207                   {
208                           my ($pkg, $ioe) = @_;
209                           my $newfh = $ioe->accept()
210                   }
211
212       ie_read_ready($handler, $ioe, $underlying_file_handle)
213           If autoreading is turned off then this will be invoked.
214
215       ie_werror($handler, $ioe, $output_buffer_reference)
216           A write error has occured when trying to drain the write buffer.
217           Provide an empty subroutine if you don't care.
218

OPTIONAL HANDLERS

220       These handler methods will be called if they are defined but it is not
221       required that they be defined.
222
223       ie_eof($handler, $ioe, $input_buffer_reference)
224           This is invoked when the read-side of the filehandle has been
225           closed by its source.
226
227       ie_output
228           This is invoked when data has just been written to the underlying
229           filehandle.
230
231       ie_outputdone
232           This is invoked when all pending data has just been written to the
233           underlying filehandle.
234
235       ie_connected
236           This is invoked when a "connect()" completes.
237
238       ie_connect_failed($handler, $ioe, $error_code)
239           This is invoked when a "connect()" fails.  For a timeout, the error
240           code will be ETIMEOUT.
241
242       ie_died($handler, $ioe, $method, $@)
243           If another handler calls "die" then ie_died will be called with the
244           IO::Event object, the name of the method just invoked, and the die
245           string.  If no ie_died() callback exists then execution will
246           terminate.
247
248       ie_timer
249           This is invoked for timer events.
250
251       ie_exception
252           Invoked when an exceptional condition arises on the underlying
253           filehandle
254
255       ie_outputoverflow($handler, $ioe, $overflowing,
256       $output_buffer_reference)
257           Invoked when there is too much output data and the output buffers
258           are overflowing.  You can take some action to generate less output.
259           This will be invoked exactly once (with $overflowing == 1) when
260           there is too much data in the buffer and then exactly once again
261           (with $overflowing == 0) when there is no longer too much data in
262           the buffer.
263

METHODS

265       In addition to methods described in detail below, the following methods
266       behave like their "IO" (mostly "IO::Socket") counterparts (except for
267       being mostly non-blocking...):
268
269               connect
270               listen
271               open
272               read
273               sysread
274               syswrite
275               print
276               eof
277               shutdown
278
279       Through AUTOLOAD (see the SUBSTITUTED METHODS section) methods are
280       passed to underlying "Event" objects:
281
282               loop
283               unloop
284               and many more...
285
286       Through AUTOLOAD (see the SUBSTITUTED METHODS section) methods are
287       passed to underlying "IO" objects:
288
289               fileno
290               stat
291               truncate
292               error
293               opened
294               untaint
295               and many more...
296
297       IO::Event defines its own methods too:
298
299       ->accept($handler, %options)
300           accept() is nearly identical to the normal IO::Socket::accept()
301           method except that instead of optionally passing a class specifier
302           for the new socket, you optionally pass a handler object or class.
303           The returned filehandle is an IO::Event object.
304
305           Supported options:
306
307           description
308               Sets the description for the new socket
309
310           autoread
311               Set to 0 if you do not want auto-read
312
313       ->can_read($amount)
314           Returns true if $amount bytes worth of input is available for
315           reading.  Note: this does not return true at EOF so be careful not
316           to hang forever at EOF.
317
318       ->getsome($amount)
319           Returns $amount bytes worth of input or undef if the request can't
320           be filled.  Returns what it can at EOF.
321
322       ->get()
323           get() is like getline() except that it pre-chomp()s the results and
324           assumes the input_record_separator is "\n".  This is like get()
325           from Data::LineBuffer.
326
327       ->unget()
328           Push chomp()ed lines back into the input buffer.  This is like
329           unget() from Data::LineBuffer.
330
331       ->ungetline(), ->xungetc(), ->ungets()
332           This is what ungetc() should be: it pushes a string back into the
333           input buffer.  This is unlike IO::Handle->ungetc which takes an
334           ordinal and pushes one character back into the the input buffer.
335           This is like FileHandle::Unget.
336
337       ->handler($new_handler)
338           Sets the handler object/class if $new_handler is provided.  Returns
339           the old handler.
340
341       ->filehandle()
342           Returns the underlying "IO::Handle".
343
344       ->event()
345           Returns the underling "Event".
346
347       ->listener($listening)
348           Used to note that a filehandle is being used to listen for
349           connections (instead of receiving data).  A passed parameter of 0
350           does the opposite.  Returns the old value.  This is mostly used
351           internally in IO::Event.
352
353       ->input_record_separator($new_sep)
354           IO::Handle doesn't allow input_record_separator's on a per
355           filehandle basis.  IO::Event does.  If you don't ever set a
356           filehandle's input record separator, then it contineously defaults
357           to the current value of $/.  If you set it, then it will use your
358           value and never look at $/ again.
359
360       ->readevents($readevents)
361           Get/set listening for read-ready events on the underlying
362           filehandle.  This could be used by ie_outputoverflow to control
363           input flows.
364
365       ->output_bufsize($output_bufsize)
366           Get/set the size of the output buffer.
367
368       ->autoread($autoread)
369           Get/set automatic reading if data when data can be read.  Without
370           autoread turned on, the input buffer ins't filled and none of the
371           read methods will work.  The point of this is for working with non-
372           data filehandles.  This is an experts-only method that kinda
373           defeats the purpose of this module.  This would be necessary using
374           recv() to get data.
375
376       ->drain()
377           Used to start looking for write-ready events on the underlying
378           filehandle.  In normal operation this is handled automatically.
379           Deprecated: use writeevents(1) instead.
380
381       ->reentrant($reentrant)
382           Get/set reentrant callbacks.  By default, IO::Event avoids making
383           reentrant callbacks.  This is good because your code is less likely
384           to break.  This is bad because you won't learn about things right
385           away.  For example, you will not learn the the output buffer is
386           overflowing during print().  You'll have to wait for the output
387           buffer to begin draining to find out.  This could be a problem.
388
389       ->close()
390           If there is output buffered, close will be delayed until the output
391           buffer drains.
392
393       ->forceclose
394           Close close immediately, even if there is output buffered.
395
396       ->ie_desc([new description])
397           Returns (and sets) the text description of the filehandle.  For
398           debugging.
399

TIMER API

401       The following timer construction arguments are supported by IO::Event's
402       emulated event loop and IO::Event's API on top of AnyEvent:
403
404       cb  A callback to invoke when the timer goes off.  The callback can
405           either be a CODE reference or an array reference.  If it's an array
406           reference, the array should be a two element tuple: the first
407           element is an object and the second object is a method to invoke on
408           the object.  The only argument to the method call a reference to
409           the timer object:
410
411            my ($object, $method) = @{$timer->{cb}}
412            $object->$method($timer)
413
414       at  A time at which to invoke the callback.
415
416       interval
417           An interval, in seconds between repeat invocations of the callback.
418
419       after
420           The interval until the first invocation of the callback.  After
421           that, invoke every interval.
422
423       The following methods (from Event) are supported on timer objects:
424       start(), again(), now(), stop(), cancel(), is_cancelled(),
425       is_running(), is_suspended(), pending.
426

IDLE API

428       The following idle construction arguments are supported by IO::Event's
429       emulated event loop and IO::Event's API on top of AnyEvent:
430
431       cb  A callback to invoke when the event loop is idle.  The callback can
432           either be a CODE reference or an array reference.  If it's an array
433           reference, the array should be a two element tuple: the first
434           element is an object and the second object is a method to invoke on
435           the object.
436
437            my ($object, $method) = @{$timer->{cb}}
438            $object->$method();
439
440       min The minimum time between invocations of the callback.
441
442       max The maximum time between invocations of the callback.
443
444       The following methods (from Event) are supported on idle objects:
445       start(), again(), now(), stop(), cancel(), is_cancelled(),
446       is_running(), is_suspended(), pending.
447

SUBSTITUED METHODS

449       Any method invocations that fail because the method isn't defined in
450       IO::Event will by tried twice more: once using trying for a method on
451       the inner (hidden) filehandle and once more trying for a method on the
452       Event object that's used to create the select loop for this module.
453
454       This dispatch is now deprecated with the choice of event handlers.
455

EXAMPLE SERVER

457               # This is a tcp line echo server
458
459               my $listener = IO::Event::Socket::INET->new(
460                       Listen => 10,
461                       Proto => 'tcp',
462                       LocalPort => 2821,
463               );
464
465               Event::loop();
466
467               sub ie_connection
468               {
469                       my ($pkg, $lstnr) = @_;
470                       my $client = $lstnr->accept();
471                       printf "accepted connection from %s:%s\n",
472                               $client->peerhost, $client->peerport;
473               }
474
475               sub ie_input
476               {
477                       my ($pkg, $client, $ibufref) = @_;
478                       print $client <$client>;
479               }
480

SYSREAD and EOF

482       sysread() is incompatible with eof() because eof() uses getc().  Most
483       of the time this isn't a problem.  In other words, some of the time
484       this is a problem: lines go missing.
485
486       For this reason, IO::Event never uses sysread().  In fact, if you ask
487       it to do a sysread() it does a read() for you instead.
488
489       On the other hand, at the current time no problems with syswrite have
490       come to light and IO::Event uses syswrite and never any other form of
491       write/print etc.
492

DESTRUCTION

494       IO::Event keeps copies of all of its registered filehandles.  If you
495       want to close a filehandle, you'll need to actually call close on it.
496

DATA STRUCTURE

498       The filehandle object itself is a funny kind of hash reference.  If you
499       want to use it to store your own data, you can.  Please don't use hash
500       keys that begin "ie_" or "io_" as those are the prefixes used by
501       "IO::Event" and "IO::Socket".
502
503       The syntax is kinda funny:
504
505               ${*$filehandle}{'your_hash_key'}
506

SEE ALSO

508       For a different API on top of IO::Event, see IO::Event::Callback.  It
509       uses IO::Event but provides a simpler and perhaps easier-to-use API.
510
511       The following perl modules do something that is kinda similar to what
512       is being done here:
513
514       AnyEvent::Handle, AnyEvent::AIO, IO::AIO, IO::Multiplex,
515       IO::NonBlocking, IO::Select Event, POE, POE::Component::Server::TCP,
516       Net::Socket::NonBlock, Net::Server::Multiplex, NetServer::Generic
517
518       The API borrows most heavily from IO::Multiplex.  IO::Event uses
519       Event.pm and thus can be used in programs that are already using Event
520       or POE.
521
522       Since the original writing of IO::Event, AnyEvent has been released and
523       now AnyEvent::AIO and <AnyEvent:Handle> should be considered the only
524       good alternatives to IO::Event.
525
526       For an example program using IO::Event, see IO::Event::rinetd which
527       used to be included in this package.
528

BUGS

530       The test suite only covers 40% of the code.  The module is used by its
531       author and seems solid.
532

LICENSE

534       Copyright (C) 2002-2009 David Muir Sharnoff <muir@idiom.org>.
535       Copyright (C) 2011-2013 Google, Inc.  This module may be
536       used/copied/etc on the same terms as Perl itself.
537
538       This module is packaged for Fedora by Emmanuel Seyman
539       <emmanuel@seyman.fr>
540

POD ERRORS

542       Hey! The above document had some coding errors, which are explained
543       below:
544
545       Around line 476:
546           '=item' outside of any '=over'
547
548
549
550perl v5.34.0                      2021-07-22                      IO::Event(3)
Impressum