IO::Event(3)
π IO::Event(3) π
β¨ NAME β¨
IO::Event β Tied Filehandles for Nonblocking IO with Object Callbacks
Okay so bestie, this is literally IO::Event: the module for Tied Filehandles for Nonblocking IO with Object Callbacks. That's the whole vibe. π¦
πΈ SYNOPSIS πΈ
Here's the quick-start mood board, untouched and exact:
use IO::Event;
use IO::Event 'emulate_Event';
use IO::Event 'AnyEvent';
my $ioe = IO::Event->new($filehandle);
my $ioe = IO::Event::Socket::INET->new( [ARGS] )
my $ioe = IO::Event::Socket::UNIX->new( [ARGS] )
my $timer = IO::Event->timer(
[after => $seconds],
interval => $seconds,
cb => CODE);
my $idler = IO::Event->idle(
[min => $seconds],
[max => $seconds],
[reentrant => 0],
cb => CODE);
IO::Event::loop();
IO::Event::unloop_all();
π DESCRIPTION π
IO::Event gives you an object-based callback system for handling nonblocking IO. The design goal is to just do the right thing w/o you needing to think about it much. β¨
All APIs are kept as simple as possible, yet at the same time, all functionality is accesible if needed. Simple things are easy. Hard things are possible. π
Most of the time file handling syntax will work fine: <$filehandle> and print $filehandle 'stuff'.
IO::Event provides automatic buffering of output (with a callback to throttle). It provides automatic line-at-a-time input.
After initial setup, call IO::Event::loop(). π
IO::Event was originally written to use Event. IO::Event still defaults to using Event but it can now use AnyEvent or its own event loop. π¦
π CHOOSING AN EVENT HANDLER π
Until you create your first IO::Event object, you can choose which underlying event handler to use. The default is Event. To choose an event handler, use one of the following lines, import no_emulate_Event, emulate_Event, or AnyEvent.
use IO::Event 'no_emulate_Event'
use IO::Event 'emulate_Event'
use IO::Event 'AnyEvent'
The no_emulate_Event option means: use Event. The emulate_Event option means IO::Event should use its own event loop.
Why?
You should use AnyEvent if you want to have compatibility with other event loops. You should use emulate_Event if you don't need compatibility with other event loops and you have missing-event bugs when using Event. You should use Event if it works for you. π«Ά
The APIs are a bit different depending on which event loop you're using.
π« Event π«
To use Event's event loop:
use IO::Event 'no_emulate_Event';
or just:
use IO::Event
IO::Event's definition for loop(), timer(), idle() and unloop_all() all default to the Event version unless emulate_Event or AnyEvent have been imported. This allows you to easily switch back and forth between Event's API and the others. π
π AnyEvent π
To use AnyEvent's select loop, import AnyEvent.
use IO::Event 'AnyEvent';
You can use AnyEvent's API directly or you can use IO::Event's emulated APIs: IO::Event::loop(), IO::Event::unloop(), IO::Event::timer(), and IO::Event::idle(). These behave like Event's routines of the same name but use AnyEvent underneath.
During testing, using the pure-perl event loop of AnyEvent::Impl::Perl from AnyEvent version 5.271, some read events were dropped. π To work around this, a synthetic read-ready event is dispatched for all connected read filehandles every two seconds. Turn this off or adjust its frequency by changing $IO::Event::AnyEvent::lost_event_hack. A numeric value is the time (in seconds) between dispatching read events. A false value turns off this performance-sapping hack. π
AnyEvent only provides basic support for idle() events: it promises to invoke them "every now and then".
π§ emulate_Event π§
To use IO::Event's own select loop, import emulate_Event.
use IO::Event 'emulate_Event';
IO::Event does not provide a complete emulation of everything that Event does. It provides the full timer API:
my $timer = IO::Event::timer( [ARGS] )
instead of
my $timer = Event::timer( [ARGS] )
However it does not provide timer events on filehandles, nor does it provide events for signals, or variable accesses.
Use IO::Event::loop() instead of Event::loop(). Use IO::Event::unloop_all() instead of Event::unloop_all(). Use IO::Event::idle() instead of Event::idle(). It does not provide any other methods or functions from Event. If you need them, please send a patch. π«Ά
π CONSTRUCTORS π
Okay, here's where you actually build the thing. β¨
IO::Event->new($filehandle, [ $handler, [ $options ]])β The basicnewconstructor takes a filehandle and returns a psuedo-filehandle. Treat theIO::Eventobject as a filehandle. Do not use the original filehandle without good reason (let us know if you find a good reason so we can fix the problem). π
The handler is the class or object where you provide callback functions to handle IO events. It defaults to the package of the calling context.
If present, $options is a hash reference with the following possible keys:
descriptionβ A text description of this filehandle. Used for debugging and error messages.read_onlyβ Set to true if this is a read-only filehandle. Do not accept output.write_onlyβ Set to true if this is a write-only filehandle. Do not attept to read.autoreadβ Set to 0 if this should not be an auto-read filehandle.
IO::Event::Socket::INET->new( [ARGS] )β This constructor usesIO::Socket::INET->new()to create a socket using the ARGS provided. It returns anIO::Eventobject. π¦
The handler defaults as above or can be set with an additional pseudo-parameter for IO::Socket::UNIX->new(): Handler. A description for the socket can be provided with an additional psuedo-parameter: Description.
IO::Event::Socket::UNIX->new( [ARGS] )β This constructor usesIO::Socket::UNIX->new()to create a socket using the ARGS provided. It returns anIO::Eventobject. π¦
The handler defaults as above or can be set with an additional pseudo-parameter for IO::Socket::UNIX->new(): Handler. A description for the socket can be provided with an additional psuedo-parameter: Description.
πΈ MANDATORY HANDLERS πΈ
These handler methods must be available in the handler object/class if the situation in which they would be called arises. No cap. π
ie_input($handler, $ioe, $input_buffer_reference)β Invoked when there is fresh data in the input buffer. The input can be retrieved via directly reading it from$$input_buffer_referenceor viaread()from the$ioefilehandle, or by using a variety of standard methods for getting data:
<$ioe> like IO::Handle
$ioe->get() like Data::LineBuffer
$ioe->read() like IO::Handle
$ioe->sysread() like IO::Handle
$ioe->getline() like IO::Handle
$ioe->getlines() like IO::Handle
$ioe->getsome() see below
$ioe->ungets() like FileHandle::Unget
At end-of-file, ie_input will only be invoked once. There may or may not be data in the input buffer. π
ie_connection($handler, $ioe)β Invoked when alisten()ing socket is ready toaccept(). It should call accept:
sub ie_connection
{
my ($pkg, $ioe) = @_;
my $newfh = $ioe->accept()
}
ie_read_ready($handler, $ioe, $underlying_file_handle)β If autoreading is turned off then this will be invoked.ie_werror($handler, $ioe, $output_buffer_reference)β A write error has occured when trying to drain the write buffer. Provide an empty subroutine if you don't care. π
π¦ OPTIONAL HANDLERS π¦
These handler methods will be called if they are defined but it is not required that they be defined. Slay. β¨
ie_eof($handler, $ioe, $input_buffer_reference)β This is invoked when the read-side of the filehandle has been closed by its source.ie_outputβ This is invoked when data has just been written to the underlying filehandle.ie_outputdoneβ This is invoked when all pending data has just been written to the underlying filehandle.ie_connectedβ This is invoked when aconnect()completes.ie_connect_failed($handler, $ioe, $error_code)β This is invoked when aconnect()fails. For a timeout, the error code will beETIMEOUT.ie_died($handler, $ioe, $method, $@)β If another handler callsdiethenie_diedwill be called with theIO::Eventobject, the name of the method just invoked, and the die string. If noie_died()callback exists then execution will terminate. πie_timerβ This is invoked for timer events.ie_exceptionβ Invoked when an exceptional condition arises on the underlying filehandleie_outputoverflow($handler, $ioe, $overflowing, $output_buffer_reference)β Invoked when there is too much output data and the output buffers are overflowing. You can take some action to generate less output. This will be invoked exactly once (with$overflowing == 1) when there is too much data in the buffer and then exactly once again (with$overflowing == 0) when there is no longer too much data in the buffer. π₯
π METHODS π
Okay bestie, so besides the methods we're about to spell out in detail, these ones behave just like their IO counterparts β mostly IO::Socket, except they're mostly non-blocking, which is the whole vibe:
connectlistenopenreadsysreadsyswriteprinteofshutdown
And through AUTOLOAD β peep the SUBSTITUTED METHODS section β some method calls get passed to the underlying Event objects:
loopunloop- and many more...
Also through AUTOLOAD, some method calls get passed to the underlying IO objects:
filenostattruncateerroropeneduntaint- and many more...
IO::Event also defines its own methods, and they are lowkey iconic:
->accept($handler, %options)β this is nearly identical to the normalIO::Socket::accept()method, except instead of optionally passing a class specifier for the new socket, you optionally pass a handler object or class. The returned filehandle is anIO::Eventobject. Supported options:descriptionβ sets the description for the new socketautoreadβ set to0if you do not want auto-read
->can_read($amount)β returns true if$amountbytes worth of input is available for reading. Note: this does not return true at EOF, so be careful not to hang forever at EOF. That would be giving stuck-in-the-group-chat energy π->getsome($amount)β returns$amountbytes worth of input, orundefif the request can't be filled. At EOF it returns what it can.->get()β likegetline(), except it pre-chomp()s the results and assumes the input_record_separator is"\n". This is likeget()fromData::LineBuffer.->unget()β pusheschomp()ed lines back into the input buffer. This is likeunget()fromData::LineBuffer.->ungetline(),->xungetc(),->ungets()β this is whatungetc()should be: it pushes a string back into the input buffer. This is unlikeIO::Handle->ungetc, which takes an ordinal and pushes one character back into the input buffer. This is likeFileHandle::Unget.->handler($new_handler)β sets the handler object/class if$new_handleris provided. Returns the old handler.->filehandle()β returns the underlyingIO::Handle.->event()β returns the underlingEventπ->listener($listening)β used to note that a filehandle is being used to listen for connections instead of receiving data. A passed parameter of0does the opposite. Returns the old value. This is mostly used internally inIO::Event.->input_record_separator($new_sep)βIO::Handledoesn't allow input_record_separator's on a per-filehandle basis.IO::Eventdoes. If you don't ever set a filehandle's input record separator, then it continuously defaults to the current value of$/. If you set it, then it will use your value and never look at$/again.->readevents($readevents)β get/set listening for read-ready events on the underlying filehandle. This could be used byie_outputoverflowto control input flows.->output_bufsize($output_bufsize)β get/set the size of the output buffer.->autoread($autoread)β get/set automatic reading of data when data can be read. Withoutautoreadturned on, the input buffer isn't filled and none of the read methods will work. The point of this is for working with non-data filehandles. This is an experts-only method that kinda defeats the purpose of this module. This would be necessary usingrecv()to get data.->drain()β used to start looking for write-ready events on the underlying filehandle. In normal operation this is handled automatically. Deprecated: usewriteevents(1)instead.->reentrant($reentrant)β get/set reentrant callbacks. By default,IO::Eventavoids making reentrant callbacks. This is good because your code is less likely to break. This is bad because you won't learn about things right away. For example, you will not learn the output buffer is overflowing duringprint(). You'll have to wait for the output buffer to begin draining to find out. This could be a problem π->close()β if there is output buffered, close will be delayed until the output buffer drains.->forcecloseβ close immediately, even if there is output buffered.->ie_desc([new description])β returns and sets the text description of the filehandle. For debugging.
β° TIMER API β°
These timer construction arguments are supported by IO::Event's emulated event loop and IO::Event's API on top of AnyEvent:
cbβ a callback to invoke when the timer goes off. The callback can either be aCODEreference or an array reference. If it's an array reference, the array should be a two element tuple: the first element is an object and the second object is a method to invoke on the object. The only argument to the method call is a reference to the timer object:
my ($object, $method) = @{$timer->{cb}}
$object->$method($timer)
atβ a time at which to invoke the callback.intervalβ an interval, in seconds, between repeat invocations of the callback.afterβ the interval until the first invocation of the callback. After that, invoke everyinterval.
The following methods from Event are supported on timer objects:
start(), again(), now(), stop(), cancel(), is_cancelled(), is_running(), is_suspended(), pending.
π΄ IDLE API π΄
These idle construction arguments are supported by IO::Event's emulated event loop and IO::Event's API on top of AnyEvent:
cbβ a callback to invoke when the event loop is idle. The callback can either be aCODEreference or an array reference. If it's an array reference, the array should be a two element tuple: the first element is an object and the second object is a method to invoke on the object.
my ($object, $method) = @{$timer->{cb}}
$object->$method();
minβ the minimum time between invocations of the callback.maxβ the maximum time between invocations of the callback.
The following methods from Event are supported on idle objects:
start(), again(), now(), stop(), cancel(), is_cancelled(), is_running(), is_suspended(), pending.
π SUBSTITUED METHODS π
Any method invocations that fail because the method isn't defined in IO::Event will be tried twice more: once trying for a method on the inner hidden filehandle, and once more trying for a method on the Event object that's used to create the select loop for this module.
This dispatch is now deprecated with the choice of event handlers. It's giving legacy era, no cap.
πΈ EXAMPLE SERVER πΈ
# This is a tcp line echo server
my $listener = IO::Event::Socket::INET->new(
Listen => 10,
Proto => 'tcp',
LocalPort => 2821,
);
Event::loop();
sub ie_connection
{
my ($pkg, $lstnr) = @_;
my $client = $lstnr->accept();
printf "accepted connection from %s:%s\n",
$client->peerhost, $client->peerport;
}
sub ie_input
{
my ($pkg, $client, $ibufref) = @_;
print $client <$client>;
}
π SYSREAD and EOF π
sysread() is incompatible with eof() because eof() uses getc(). Most of the time this isn't a problem. In other words, some of the time this is a problem: lines go missing π
For this reason, IO::Event never uses sysread(). In fact, if you ask it to do a sysread(), it does a read() for you instead.
On the other hand, at the current time no problems with syswrite have come to light, and IO::Event uses syswrite and never any other form of write/print etc.
π DESTRUCTION π
IO::Event keeps copies of all of its registered filehandles. If you want to close a filehandle, you'll need to actually call close on it. No ghosting your filehandles, bestie.
π DATA STRUCTURE π
The filehandle object itself is a funny kind of hash reference. If you want to use it to store your own data, you can. Please don't use hash keys that begin ie_ or io_, because those are the prefixes used by IO::Event and IO::Socket.
The syntax is kinda funny:
${*$filehandle}{'your_hash_key'}
π¦ SEE ALSO π¦
For a different API on top of IO::Event, see IO::Event::Callback. It uses IO::Event but provides a simpler and perhaps easier-to-use API.
The following perl modules do something that is kinda similar to what is being done here:
AnyEvent::HandleAnyEvent::AIOIO::AIOIO::MultiplexIO::NonBlockingIO::Select EventPOEPOE::Component::Server::TCPNet::Socket::NonBlockNet::Server::MultiplexNetServer::Generic
The API borrows most heavily from IO::Multiplex. IO::Event uses Event.pm and thus can be used in programs that are already using Event or POE.
Since the original writing of IO::Event, AnyEvent has been released and now AnyEvent::AIO and <AnyEvent:Handle> should be considered the only good alternatives to IO::Event.
For an example program using IO::Event, see IO::Event::rinetd, which used to be included in this package.
π BUGS π
The test suite only covers 40% of the code. The module is used by its author and seems solid. Periodt, but also π.
π LICENSE π
Copyright (C) 2002-2009 David Muir Sharnoff <muir@idiom.org>. Copyright (C) 2011-2013 Google, Inc. This module may be used/copied/etc on the same terms as Perl itself.
This module is packaged for Fedora by Emmanuel Seyman <emmanuel@seyman.fr>
π POD ERRORS π
Hey! The above document had some coding errors, which are explained below:
Around line 476:
'=item' outside of any '=over'
π Okay so that's the whole page, bestie. Source/version vibe: perl v5.42.0, dated 2016-12-07, and it's the IO::Event(3) page. Byeee, go slay some non-blocking I/O π«Άβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-IO-Event 0.813-bp160.1.12 Β· GPL-1.0+ or Artistic-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms