=head1 NAME POE - Perl Object Environment =head1 DESCRIPTION POE is a high-level, object oriented framework for writing event driven programs. Being designed to take care of most of the fiddly mucking about with select and sockets, it especially lends itself to multi-session servers and clients. POE comes with seventeen complete, commented sample/test programs in the distribution's tests subdirectory. Please see the [unknown tag L] Tests and Example Programs section near the end of this file for a brief explanation of each. F, in particular, is a quick introduction to using POE. POE's original purpose was to provide a runtime "agent space" in which objects ('bots) and users can roam and interact. However, because POE's events framework is useful by itself, it has been released without objects =over 2 =item 1 Design Goals The design goals are mostly fluff. You won't learn how to use POE by reading them. =over 2 =item 1 Simplicity POE is based on very simple ideas. Events, sessions to receive them, functions to manipulate resources. Each feature is designed for ease of use, mainly because the author intends to use them a lot. Most of the subsequent design goals overlap with POE's simplicity. =item 2 Layers POE is separated into distinct layers. Each layer adds features over previous layers without depending on subsequent ones. This allows developers to use subsets of POE without including unnecessary code. =item 3 Abstraction POE hides most of the tedious, redundant details of event-driven programming behind high-level, functional interfaces. Some of the interfaces are abstracted even further in other POE layers. This lets developers pick the level of abstraction they're comfortable with. =item 4 Flexibility POE avoids assumptions and artificial limitations wherever possible. Previous versions didn't, and it caused the author a lot of grief. =item 5 Invisibility POE provides its services cleanly and quietly. POE objects are designed to plug themselves into the events layer when they are created. They quietly perform their jobs while they exist, and they cleanly unplug themselves when they are destroyed. POE tracks its own references and collects its own garbage. =item 6 Portability Please see the README for the latest portability information. =back =back =head1 Quick Start / Tutorial This section's not written yet. The F program is a very simple, working example. It contains lots of narrative and comments. The other example programs show how to use POE for other things. =head1 Events Layer POE's events layer is implemented in two classes: C and C. C contains the event queue and resource manager. C instances are bundles of event handlers, similar to operating system processes or threads. Sessions may also be thought of as state machines. When considering POE from this point of view, event handlers become states in the machine, and events signal transitions from one state to another. The event-driven nature of POE's state machines allows them to cooperatively multi-thread within themselves and multitask with each-other. Consider this simple Perl code, for example: my $i = 0; while ($i < 100) { print $i++, "\n"; } exit; It can be represented as a finite automata (state machine) consisting of four states: 1. Set $i to 0, and go to state 2. 2. Test $i < 100. If true, go to state 3; otherwise go to state 4. 3. Display $i, increment it, and go to state 2. 4. Exit. These simplified event handlers represent the previous state machine: _start => sub { post(1); }, 1 => sub { $i = 1; post(2); }, 2 => sub { if ($i < 100) { post(3); } else { post(4); } }, 3 => sub { print $i++, "\n"; post(2); }, 4 => sub { }, # do nothing, and the session stops To be sure, this is a lot slower than the original procedural code, but it has the benefit of cooperating with itself and other sessions within the same program. =over 2 =item 1 Sessions B Processes no longer support multiple kernels. This obsoleted the C<$kernel> parameter for session constructors, and it was removed. Sessions are POE's basic, self-contained units of execution. They are equivalent to processes or threads in real operating systems. Sessions register themselves with POE's kernel when they are created. The kernel manages their resources until they stop. =over 2 =item 1 Session Methods These are C's public methods. =over 2 =item 1 C C toggles the session's options flags. B{'_debug'}> in version 0.06.> Currently, options are mostly for debugging: =over 2 =item * trace - Boolean. Trace events as they arrive at the session. =item * default - Boolean. Note events that can't be handled. =back $_[SESSION]->option( trace => 1, default => 0 ); Boolean values may be either C<1>, C<0>, C<'on'>, C<'off'>, C<'yes'> or C<'no'>. C only changes the options that are present as parameters. All other options are left alone. =back =item 2 Session Types There currently are four kinds of sessions: Inline, Object, Package and Hybrid. Each type provides a way to build sessions from different kinds of event handlers, and each has a different constructor syntax. =over 2 =item 1 Inline Sessions Inline sessions consist of event names, each followed by a reference to the code that handles the event. new POE::Session( name1 => \&name1_handler, # handles the "name1" event name2 => sub { ... }, # handles the "name2" event \@start_args, # ARG0..ARGn for the _start event ); Events delivered to inline sessions have C in their C parameters. =item 2 Object Sessions Object sessions consist of blessed object references, each followed by a reference to an array of events that the object will handle. Each object must have methods named after the events it handles. Remember that C<=E<62>> stringifies its left value. Using it for object sessions will cause object references to lose their blessing. my $object1 = new SomeObject(...); my $object2 = new SomeOtherObject(...); new POE::Session( $object1, [ 'name1', 'name2' ], $object2, [ 'name3', 'name4' ], \@start_args, ); Events delivered to object sessions have a reference to the object in their C parameters. sessions. =item 3 Package Sessions Package sessions are similar to object sessions, but they use package names instead of object references. The C<=E<62>> operator works for this one. Event handlers are called as package new POE::Session( $package, [ 'name1', # $package->'name1' handles "name1" 'name2' # $package->'name2' handles "name2" ], \@start_args, ); Events delivered to package sessions have the package name in their C parameters. =item 4 Hybrid Sessions Hybrid objects contain a mix of available event handlers. my $object1 = new SomeObject(...); my $object2 = new SomeOtherObject(...); new POE::Session( \@start_args, $object1, [ 'name11', 'name12' ], 'name01' => sub { ... }, 'name02' => sub { ... }, $object2, [ 'name21', 'name22' ], 'name03' => sub { ... }, 'name04' => sub { ... }, $package3, [ 'name31', 'name32' ], ); Events delivered to hybrid sessions have various values for C. The particular value depends on how the event handler was registered. =back =back =item 2 About Event Handlers Event handlers are evaluated in a scalar context. Handlers may use array references if they need to return multiple values. Return values are used by signal handlers, to tell the kernel whether or not the signal was handled. They also are returned to the caller if an event handle is called directly. See B<_signal> or C for more on that. If an event handler returns a reference to a POE object, it will be stringified. This is done to prevent "blessing bleed" (see the Changes file) from interfering with POE's garbage collection. The code that checks for POE objects does not look inside data passed by reference-- it's just there to catch accidents, like this example: sub stop_handler { delete $_[HEAP]->{'readwrite wheel'}; # reference to the readwrite wheel is implicitly returned } That accidentally returns a reference to a POE::Wheel::ReadWrite object. If the reference was not stringified, it would delay the wheel's destruction until after the session stopped. The wheel would try to remove its states from the nonexistent session, and a runtime error would occur. =item 3 Kernel The C class contains POE's event loop and functions to manage events and other resources. =over 2 =item 1 Kernel Management B Support for multiple kernels has been removed, enabling better signal support in 0.06 and simplifying threads support in the future. As a result, explicitly creating kernels has been deemed silly and is now handled by C the first time it's used. The C method still exists, and nothing will break if it's called, but it's just not necessary now. The program's single kernel is automatically initialized the first time C is used. C exports C<$poe_kernel>, a reference to the global kernel, each time it's used. =over 2 =item 1 C This starts the kernel's event loop. It will not return until all the sessions it manages end. There are two corollaries: If there are no sessions, it will end immediately; and if sessions never exit, neither will C. # includes POE::Kernel and POE::Session by default use POE; # set up initial sessions here $poe_kernel->run(); exit; =back =item 2 Events Events inform sessions when it is time to do something. In turn, sessions invoke their corresponding handlers. For example, when a session receives a B<_start> event, it invokes its event handler named C<'_start'>. There are two ways to send events to sessions. Events can be posted, in which case the kernel queues them and dispatches them in FIFO order. Event handlers can also be called immediately, bypassing the queue. Immediate calls can be useful for critical code or events that should not be delayed. POE's wheels use C to minimize event latency. =over 2 =item 1 Event Management Functions These functions manage events. No, really! =over 2 =item 1 C C places an event in the kernel's queue. The kernel dispatches queued events in FIFO order. Event handlers are evaluated in a scalar context, and their return values are discarded. $kernel->post($destination_session, $event_name, @args); Whatever the C<$event_name> handler returns is lost. If a return value is important, there are two ways to get it. First, have the C<$destination_session> post a return event to C<$_[FROM]>; second, use C. =item 2 C C is an alias for posting an event to the current session. It does not operate like C in real thread libraries (swapping stacks in plain Perl is a hard thing to do). C does not need a C<$destination_session> parameter because the kernel already knows which session is running. Event handlers are evaluated in a scalar context, and their return values are discarded. $kernel->yield($event_name, @args); =item 3 C C immediately dispatches an event to its session. Event handlers are evaluated in a scalar context, and C returns their return values. my $handler_return_value = $kernel->call( $destination_session, $event_name, @args ); C can exercise bugs in Perl and/or the C library (we're not sure which just yet). This only seems to occur while destroying an event handler from another event handler that is directly called by the first one. Until this is fixed, if your POE program dumps core with a SIGSEGV, change your C invocations to C and they should go away. =back =item 2 Event Handler Parameters B Prior to version 0.06, inline handlers received different parameters than object and package handlers. The call signatures have been unified in version 0.06. This breaks programs written with POE 0.05 or earlier. To prevent future breakage, C now exports constants for parameters' offsets into C<@_>. Programs that use them guaranteed not to break if existing parameters are rearranged or new ones are added. If parameters are removed in the future, programs will break at compile time instead of silently failing during runtime. Parameters may be used discretely as C<$_[KERNEL]>. If several parameters are needed multiple times, it may be faster to assign them to lexicals all at once with an array slice: my ($kernel, $operation, $errnum, $errstr) = @_[KERNEL, ARG0, ARG1, ARG2]; The parameter constants are: =over 2 =item 1 C C<$_[OBJECT]>'s value depends on the type of event handler. For inline handlers, it is C. For object handlers, it contains a reference to the object that owns the handler. For package handlers, it contains the name of the package. =item 2 C C<$_[KERNEL]> is a reference to the kernel that is managing this session. It is provided in case the event handler was defined in a scope where C<$poe_kernel> is unavailable. =item 3 C C<$_[SESSION]> is a reference to the current session object. Direct manipulation of its contents and methods is not supported. It is included for use as a parameter to C methods. =item 4 C C<$_[HEAP]> is a reference to a hash set aside for sessions to store global data. Information stored in the heap will be available to all the event handlers in the session, and it will persist until the session stops. POE will delete the heap from its internal structures, but developers are expected to remove anything from it that would leak memory. B (formerly known as C<$me> or C<$namespace>) as an alias for C in Kernel method calls is depreciated in version 0.06, and it will be removed in version 0.07.> =item 5 C C<$_[FROM]> is a reference to the session that sent the event. It is suitable as a destination for responses. If using C in both directions, be aware that POE does not prevent deep recursion. =item 6 C C<@_[ARG0 .. ARG9]> are the first ten elements of C<@args> as passed to C, C, C or C. If more than ten items are needed, they may be referenced as C<$_[ARG9+1..]>, but it would be more efficient to pass them all as an array reference in C. =back =item 3 Predefined Events E<38> Parameters POE reserves some event names for internal and standard use. All its predefined events begin with an underscore, and future ones will too. It may be wise to avoid leading underscores in your own event names. Every predefined event is accompanied by C, C, C, C and C. =over 2 =item 1 B<_start> Sessions register themselves with the kernel when they are created. Kernels dispatch B<_start> events to sessions when the registration is complete. Sessions may then begin interacting with the kernel in a sane way. POE requires every session to have a C<_start> handler, otherwise how would they know when it's okay to start? C contains a reference to the session that started this session. C contain arguments as they were given to the session constructor. =item 2 B<_stop> Kernels keep track of the resources that sessions use. Some resources guarantee that the session will receive events. These include enqueued events, selects (filehandle monitors), child sessions, and aliases. Sessions that run out of these resources become starved for events, and kernels removes them. Before it removes them, it issues a C<_stop> event. This gives sessions an opportunity to clean up. C is the session that posted the B<_stop> event. In the case of resource starvation, this is the C. If B<_stop> was posted, it contains a reference to the session that posted it. C are empty in the case of resource starvation. If the B<_stop> event was posted, they may contain other values. =item 3 B<_signal> B POE sets handlers for most of the signals in C<%SIG>. The only exceptions are things which might exist in C<%SIG> but probably shouldn't. POE will not register a signal handler for C, for example, because doing so breaks Perl for HP-UX. Signals are propagated to children of the destination session first. Since every session ultimately is a descendent of the kernel, posting signals to the kernel guarantees that every session receives them. POE does not magically solve Perl's problems with signals. Yet. Currently there are three types of signals. The kernel processes each in a different way: C causes a B<_signal> event to be posted directly to the session that is running when the signal was received. C contains the signal name as it appears in C<%SIG>. C and/or C call C to acquire the dying child's process ID. A B<_signal> event will be posted to all sessions if the child PID is valid. C contains C regardless of the actual signal name, C contains the child PID, and C contains the contents of C<$?> just after the C call. All other signals cause a B<_signal> event to be posted to all sessions. C contains the signal name as it appears in C<%SIG>. =item 4 B<_garbage_collect> The B<_garbage_collect> event tells the kernel to check a session's resources and stop it if none are left. It never is dispatched to a session. This was added to delay garbage collection for new sessions, allowing parent sessions to interact with them before they stop. =item 5 B<_parent> The B<_parent> event lets child sessions know that they are about to be orphaned, and it tells them their new parents. It is dispatched to child sessions before parents receive their B<_stop> events. C should always equal C. If it does not, then the event was sent by a session other than the kernel. C is this session's old parent; C is the new parent. =item 6 B<_child> The B<_child> event is sent to parent sessions when they acquire or lose child sessions. B<_child> is dispatched to parents after the children receive B<_start> or before they receive B<_stop>. C should always equal C. If it does not, then the event was sent by a session other than the kernel. C indicates what is happening to the child. It is C<'gain'> if the session is a grandchild being given by a dying child. It is C<'lose'> if the session is itself a dying child. It is C<'create'> if the child was created by the current session. C is a reference to the child session. It will still be valid, even if the child is in its death throes. C is only valid when C contains C<'create'>. It contains the return value of the child's B<_start> event handler, which was evaluated in a scalar context (and stringified if it was a reference to a POE::* object). =item 7 B<_default> The B<_default> handler is invoked whenever a session receives an event it can't handle. The event is discarded if the session doesn't have a B<_default> handler. This prevents POE from recursing until perl's stack eats the machine. C contains the name of the original event. C contains a reference to the original event's C parameters. B<_default> can be useful for detecting misspelled event names or handling strange signals. So can C. =back =back =item 3 Alarms Alarms are just events that are scheduled to be dispatched at some point in the future. POE will use C, if it's available, to allow fractional alarm times. =over 2 =item 1 C C enqueues an event with a future dispatch time, specified in seconds since the unix epoch. $kernel->alarm($event_name, $dispatch_time, @args); If C<$dispatch_time> is in the past, it will be clipped to C