Scroll to navigation

POE(3pm) User Contributed Perl Documentation POE(3pm)

NAME

POE - portable multitasking and networking framework for any event loop

SYNOPSIS

  #!/usr/bin/perl
  use warnings;
  use strict;
  use POE;  # Auto-includes POE::Kernel and POE::Session.
  sub handler_start {
    my ($kernel, $heap, $session) = @_[KERNEL, HEAP, SESSION];
    print "Session ", $session->ID, " has started.\n";
    $heap->{count} = 0;
    $kernel->yield('increment');
  }
  sub handler_increment {
    my ($kernel, $heap, $session) = @_[KERNEL, HEAP, SESSION];
    print "Session ", $session->ID, " counted to ", ++$heap->{count}, ".\n";
    $kernel->yield('increment') if $heap->{count} < 10;
  }
  sub handler_stop {
    print "Session ", $_[SESSION]->ID, " has stopped.\n";
  }
  for (1..10) {
    POE::Session->create(
      inline_states => {
        _start    => \&handler_start,
        increment => \&handler_increment,
        _stop     => \&handler_stop,
      }
    );
  }
  POE::Kernel->run();
  exit;

DESCRIPTION

POE is a framework for cooperative, event driven multitasking andnetworking in Perl. Other languages have similar frameworks. Pythonhas Twisted. TCL has "the event loop".

POE provides a unified interface for several other event loops,including select(), IO::Poll, Glib, Gtk, Tk, Wx, and Gtk2. Many of these event loop interfaces were written by others, with the help of POE::Test::Loops. They may be found on the CPAN.

POE achieves its high degree of portability to different operatingsystems and Perl versions by being written entirely in Perl. CPANhosts optional XS modules for POE if speed is more desirable thanportability.

POE is designed in layers. Each layer builds atop the lower levelones. Programs are free to use POE at any level of abstraction, anddifferent levels can be mixed and matched seamlessly within a singleprogram. Remember, though, that higher-level abstractions oftenrequire more resources than lower-level ones. The conveniences theyprovide are not free.

POE's bundled abstraction layers are the tip of a growing iceberg.Sprocket, POE::Stage, and other CPAN distributionsbuild upon this work. You're encouraged to look around.

No matter how high you go, though, it all boils down to calls toPOE::Kernel. So your down-to-earth code can easilycooperate with stratospheric systems.

Layer 1: Kernel and Sessions

The lowest public layer is comprised of POE::Kernel,POE::Session, and other session types.

POE::Kernel does most of the heavy lifting. It provides a portableinterface for filehandle activity detection, multiple alarms and othertimers, signal handling, and other less-common features.

POE::Session and derived classes encapsulate the notion of an eventdriven task. They also customize event dispatch to a particularcalling convention. POE::NFA, for example, is more of a proper statemachine. The CPAN has several other kinds of sessions.

Everything ultimately builds on these classes or the concepts theyimplement. If you're short on time, the things to read besides thisare POE::Kernel and POE::Session.

Layer 2: Wheels, Filters, and Drivers

POE::Wheel objects are dynamic mix-ins for POE::Session instances. These"wheels" perform very common, generic tasks in a highly reusable andcustomizable way. POE::Wheel::ReadWrite, forexample, implements non-blocking buffered I/O. Nearly everybody needs this,so why require people to reinvent it all the time?

POE::Filter objects customize wheels in a modular way. Filters act asI/O layers, turning raw streams into structured data, and serializingstructures into something suitable for streams. The CPAN also has severalof these.

Drivers are where the wheels meet the road. In this case, the road issome type of file handle. Drivers do the actual reading and writingin a standard way so wheels don't need to know the difference betweensend() and syswrite().

POE::Driver objects get relatively short shrift because very few areneeded. The most common driver, POE::Driver::SysRW is ubiquitous andalso the default, so most people will never need to specify one.

Layer 3: Components

POE::Component classes are essentially Perl classes that use POE toperform tasks in a non-blocking or cooperative way. This is a verybroad definition, and POE components are all over the abstraction map.

Many components, such as POE::Component::Server::SMTP, encapsulate thegeneric details of an entire application. Others perform rathernarrow tasks, such as POE::Component::DirWatch::Object.

POE components are often just plain Perl objects. The previouslymentioned POE::Component::DirWatch::Object uses Moose. Other objectand meta-object frameworks are compatible.

Also of interest is POE::Component::Generic, which allows you to createa POE component from nearly any blocking module.

There are quite a lot of components on the CPAN.<http://search.cpan.org/search?query=poe+component&mode=all>

Layer 4 and Beyond: Frameworks and Object Metaphors

It's possible to abstract POE entirely behind a different framework.In fact we encourage people to write domain-specific abstractions thatentirely hide POE if necessary. The nice thing here is that even atthese high levels of abstraction, things will continue to interoperateall the way down to layer 1.

Two examples of ultra-high level abstraction are Sprocket, a networkingframework that does its own thing, and POE::Stage, which is POE'screator's attempt to formalize and standardize POE components.

It is also possible to communicate between POE processes. This is calledIKC, for Inter-Kernel Communication. There are a few IKC components on the CPAN (<http://search.cpan.org/search?query=IKC&mode=all>), notably POE::Component::IKC and POE::TIKC.

Layer 0: POE's Internals

POE's layered architecture continues below the surface. POE's gutsare broken into specific POE::Loop classes for each eventloop it supports. Internals are divided up by type, givingPOE::Resource classes for Aliases, Controls, Events,Extrefs, FileHandles, SIDs, Sessions and Signals.

POE::Kernel's APIs are extensible through POE::API mix-in classes.Some brave souls have even published new APIs on CPAN, such asPOE::API::Peek (which gives you access to some of the internalPOE::Resource methods).

By design, it's possible to implement new POE::Kernel guts by creatinganother POE::Resource class. One can then expose the functionality witha new POE::API mix-in.

DOCUMENTATION ROADMAP

You're reading the main POE documentation. It's the general entrypoint to the world of POE. You already know this, however, so let'stalk about something more interesting.

Basic Features

POE's basic features are documented mainly in POE::Kernel andPOE::Session. Methods are documented in the classes that implementthem. Broader concepts are covered in the most appropriate class, andsometimes they are divided among classes that share in theirimplementation.

Basic Usage

Basic usage, even for POE.pm, is documented in POE::Kernel. That'swhere most of POE's work is done, and POE.pm is little more than aclass loader.

@_[KERNEL, HEAP, etc.]

Event handler calling conventions, that weird @_[KERNEL, HEAP] stuff, is documented in POE::Session. That's because POE::Session implements the calling convention, and other session types often do it differently.

Base Classes Document Common Features

The POE::Wheel, POE::Driver,POE::Filter, and POE::Component baseclasses describe what's common among each class. It's a good idea to atleast skim the base class documentation since the subclasses tend not torehash the common things.

POE::Queue, POE::Resource, and POE::Loop document theconcepts and sometimes the standard interfaces behind multiplesubclasses. You're encouraged to have a look.

Helper Classes

POE includes some helper classes for portability. POE::Pipe, and itssubclasses POE::Pipe::OneWay and POE::Pipe::TwoWay are portable pipes.

Event Loop Bridges

POE::Loop documents and specifies the interface for all of POE's eventloop bridges. The individual classes may document specific details,but generally they adhere to the spec strongly enough that they don'tneed to.

Many of the existing POE::Loop bridges provided in POE's basedistribution will move out to separate distributions shortly. Thedocumentation will probably remain the same, however.

POE::Queue and POE::Queue::Array

POE's event queue is basically a priority heap implemented as anordered array. POE::Queue documents the standard interface for POEevent queues, and POE::Queue::Array implements the ordered arrayqueue. Tony Cook has released POE::XS::Queue::Array, which is adrop-in C replacement for POE::Queue::Array. You might give it a tryif you need more performance. POE's event queue is some of thehottest code in the system.

This Section Isn't Complete

Help organize the documentation. Obviously we can't think ofeverything. We're well aware of this and welcome audienceparticipation.

See SEE ALSO

Wherever possible, the SEE ALSO section will cross-reference onemodule to related ones.

Don't Forget the Web

Finally, there are many POE resources on the web. The CPAN contains agrowing number of POE modules. <http://poe.perl.org/> hosts POE'swiki, which includes tutorials, an extensive set of examples,documentation, and more. Plus it's a wiki, so you can trivially pitchin your two cents.

SYSTEM REQUIREMENTS

POE's basic requirements are rather light. Most are included withmodern versions of Perl, and the rest (if any) should be generallyportable by now.

Time::HiRes is highly recommended, even for older Perls that don'tinclude it. POE will work without it, but alarms and other features will bemuch more accurate if it's included. POE::Kernel will use Time::HiResautomatically if it's available.

POE::Filter::Reference needs a module to serialize data for transportingit across a network. It will use Storable, FreezeThaw, YAML, orsome other package with freeze() and thaw() methods. It can also use Compress::Zlib to conserve bandwidth and reduce latency over slow links, but it's not required.

If you want to write web servers, you'll need to install libwww-perl, whichrequires libnet. This is a small world of modules that includesHTTP::Status, HTTP::Request,HTTP::Date, and HTTP::Response. They aregenerally good to have, and modern versions of Perl even include them.

Programs that use POE::Wheel::Curses will of courserequire the Curses module, which in turn requires some sort ofcurses library.

If you're using POE with Tk, you'll need Tk installed.

And other obvious things. Let us know if we've overlooked anon-obvious detail.

COMPATIBILITY ISSUES

One of POE's design goals is to be as portable as possible. That'swhy it's written in "Plain Perl". XS versions of POE modules areavailable as third-party distributions. Parts of POE that requirenonstandard libraries are optional, and not having those librariesshould not prevent POE from installing.

Despite Chris Williams' efforts, we can't test POE everywhere. Pleasesee the GETTING HELP section if you run into a problem.

POE is expected to work on most forms of UNIX, including FreeBSD,MacOS X, Linux, Solaris. Maybe even AIX and QNX, but we're not sure.

POE is also tested on Windows XP, using the latest version ofActiveState, Strawberry and Cygwin Perl. POE is fully supported withStrawberry Perl, as it's included in the Strawberry distribution.

OS/2 and MacOS 9 have been reported to work in the past, but nobodyseems to be testing there anymore. Reports and patches are stillwelcome.

Past versions of POE have been tested with Perl versions as far backas 5.6.2 and as recent as "blead", today's development build. Wecan no longer guarantee each release will work everywhere, but we willbe happy to work with you if you need special support for a really oldsystem. You can always use older POE releases that works on your version,please check BackPAN <http://backpan.perl.org/authors/id/R/RC/RCAPUTO/>.

POE's quality is due in large part to the fine work of Chris Williamsand the other CPAN testers. They have dedicated resources towardsensuring CPAN distributions pass their own tests, and we watch theirreports religiously. You can, too. The latest POE test reports canbe found at <http://cpantesters.org/distro/P/POE.html>.

Thanks also go out to Benjamin Smith and the 2006 Google Summer ofCode. Ben was awarded a grant to improve POE's test suite, which hedid admirably.

Windows Issues

POE seems to work very nicely with Perl compiled for Cygwin. If youmust use ActiveState Perl, please use the absolute latest version.ActiveState Perl's compatibility fluctuates from one build to another,so we tend not to support older releases.

Windows and ActiveState Perl are considered an esoteric platform dueto the complex interactions between various versions. POE thereforerelies on user feedback and support here.

A number of people have helped bring POE's Windows support this far,through contributions of time, patches, and other resources. Some ofthem are: Sean Puckett, Douglas Couch, Andrew Chen, Uhlarik Ondoej,Nick Williams, and Chris Williams (no relation).

Linux/Unix Issues

pty woes

Some distributions chose to not completely setup the pseudo-ttysupport. This is needed for POE::Wheel::Run to interact with thesubprocess. If you see something like this while running "make test" please look at your distribution's documentation on how to fix it. For example, on Debian-based systems the solution was to execute "sudo apt-get install udev".

  t/30_loops/io_poll/wheel_run.t ..................... 1/99
  pty_allocate(nonfatal): posix_openpt(): No such file or directory at /usr/local/lib/perl/5.10.0/IO/Pty.pm line 24.
  ...
  Cannot open a pty at /home/apoc/poe/blib/lib/POE/Wheel/Run.pm line 251
  Compilation failed in require at t/30_loops/io_poll/wheel_run.t line 24.
  # Looks like you planned 99 tests but ran 5.
  # Looks like your test exited with 22 just after 5.
  t/30_loops/io_poll/wheel_run.t ..................... Dubious, test returned 22 (wstat 5632, 0x1600)

Other Compatibility Issues

None currently known. See GETTING HELP below if you've run intosomething.

GETTING HELP

POE's developers take pride in its quality. If you encounter aproblem, please let us know.

POE's Request Tracker

You're welcome to e-mail questions and bug reports to<bug-POE@rt.cpan.org>. This is not a realtime support channel,though. If you need a more immediate response, try one of the methodsbelow.

POE's Mailing List

POE has a dedicated mailing list where developers and users discussthe software and its use. You're welcome to join us. Send an e-mailto <poe-help@perl.org> for subscription instructions. The subject andmessage body are ignored.

POE's Web Site

<http://poe.perl.org> contains recent information, tutorials, andexamples. It's also a wiki, so people are invited to share tips andcode snippets there as well.

POE's Source Code

The following command will fetch the most current version of POE intothe "poe" subdirectory:

  git clone https://github.com/rcaputo/poe.git

SourceForge

http://sourceforge.net/projects/poe/ is POE's project page.

Internet Relay Chat (IRC)

irc.perl.org channel #poe is an informal place to waste some time andmaybe even discuss Perl and POE. Consider an SSH relay if yourworkplace frowns on IRC. But only if they won't fire you if you'recaught.

Personal Support

Unfortunately we don't have resources to provide free one-on-onepersonal support anymore. We'll do it for a fee, though. Send Roccoan e-mail via his CPAN address.

SEE ALSO

Broken down by abstraction layer.

Layer 1

POE::Kernel, POE::Session, POE::NFA

Layer 2

POE::Wheel, POE::Wheel::Curses, POE::Wheel::FollowTail,POE::Wheel::ListenAccept, POE::Wheel::ReadLine, POE::Wheel::ReadWrite,POE::Wheel::Run, POE::Wheel::SocketFactory

POE::Driver, POE::Driver::SysRW

POE::Filter, POE::Filter::Block, POE::Filter::Grep,POE::Filter::HTTPD, POE::Filter::Line, POE::Filter::Map,POE::Filter::RecordBlock, POE::Filter::Reference,POE::Filter::Stackable, POE::Filter::Stream

Layer 3

POE::Component, POE::Component::Client::TCP,POE::Component::Server::TCP

Layer 0

POE::Loop, POE::Loop::Event, POE::Loop::Gtk, POE::Loop::IO_Poll,POE::Loop::Select, POE::Loop::Tk

POE::Queue, POE::Queue::Array

POE::Resource, POE::Resource::Aliases, POE::Resource::Events,POE::Resource::Extrefs, POE::Resource::FileHandles,POE::Resource::SIDs, POE::Resource::Sessions, POE::Resource::Signals

Helpers

POE::Pipe, POE::Pipe::OneWay, POE::Pipe::TwoWay

Home Page

http://poe.perl.org/

Bug Tracker

https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=POE

Repositories and Changes

You can browse the POE source and complete change logs athttps://github.com/rcaputo/poe. It also provides an RSSnews feed for those who want to follow development innear-realtime.

Other Resources

https://metacpan.org/module/POE

http://search.cpan.org/dist/POE

AUTHORS & COPYRIGHT

POE is the combined effort of quite a lot of people. This is anincomplete list of some early contributors. A more complete list canbe found in POE's change log.

Ann Barcomb is <kudra@domaintje.com>, aka "kudra". Ann contributed large portions of POE::Simple and the code that became the ReadWrite support in POE::Component::Server::TCP. Her ideas also inspired Client::TCP component, introduced in version 0.1702.
Artur Bergman is <sky@cpan.org>. He contributed many hours' work intoPOE and quite a lot of ideas. Years later, I decide he's right andactually implement them.

Artur is the author of Filter::HTTPD and Filter::Reference, as well asbits and pieces throughout POE. His feedback, testing, design andinspiration have been instrumental in making POE what it is today.

Artur is investing his time heavily into perl 5's iThreads and PONIEat the moment. This project has far-reaching implications for POE'sfuture.

Jos Boumans is <kane@cpan.org>, aka "kane". Jos is a major driving force behind the POE::Simple movement and has helped inspire the POE::Components for TCP clients and servers.
Matt Cashner is <sungo@pobox.com>, aka "sungo". Matt is one of POE's core developers. He's spearheaded the movement to simplify POE for new users, flattening the learning curve and making the system more accessible to everyone. He uses the system in mission critical applications, folding feedback and features back into the distribution for everyone's enjoyment.
Andrew Chen is <achen-poe@micropixel.com>. Andrew is the residentPOE/Windows guru. He contributes much needed testing for Solaris onthe SPARC and Windows on various Intel platforms.
Douglas Couch is <dscouch@purdue.edu>. Douglas helped port andmaintain POE for Windows early on.
Jeffrey Goff is <jgoff@blackboard.com>. Jeffrey is the author ofseveral POE modules, including a tokenizing filter and a component formanaging user information, PoCo::UserBase. He's also co-author of "ABeginner's Introduction to POE" at www.perl.com.
Philip Gwyn is <gwynp@artware.qc.ca>. He extended the Wheels I/Oabstraction to support hot-swappable filters, and he eventuallyconvinced Rocco that unique session and kernel IDs were a good thing.

Philip also enhanced POE::Filter::Reference tosupport different serialization methods. He has also improved POE's qualityby finding and fixing several bugs. He provided POE a much needed codereview around version 0.06.

Lately, Philip tracked down the race condition in signal handling andfixed it with the signal pipe.

Arnar is <addi@umich.edu>. Addi tested POE and POE::Component::IRC onWindows, finding bugs and testing fixes. He appears throughout the Changesfile. He has also written "cpoe", which is a POE-like library for C.
Dave Paris is <dparis@w3works.com>. Dave tested and benchmarked POEaround version 0.05, discovering some subtle (and not so subtle)timing problems. The pre-forking server sample was his idea.Versions 0.06 and later scaled to higher loads because of his work.He has contributed a lot of testing and feedback, much of which istagged in the Changes file as a-mused. The man is scarily good attesting and troubleshooting.
Dieter Pearcey is <dieter@bullfrog.perlhacker.org>. He goes by severalJapanese nicknames. Dieter's current area of expertise is in Wheels andFilters. He greatly improved POE::Wheel::FollowTail, and his Filtercontributions include the basic Block filter, as well as Stackable,RecordBlock, Grep and Map.
Plixer International is at <http://plixer.com/>. Their sponsorshiphas helped POE 1.300 and beyond be significantly more robust usingiThreads, especially when using fork() in Windows.
Robert Seifer is <e-mail unknown>. He rotates IRC nicknamesregularly.

Robert contributed entirely too much time, both his own and hiscomputers, towards the detection and eradication of a memorycorruption bug that POE tickled in earlier Perl versions. In the end,his work produced a simple compile-time hack that worked around aproblem relating to anonymous subs, scope and @{} processing.

Matt contributed "POE::Kernel::Poll", a more efficient way to watch multiple files than select(). It's since been moved to POE::Loop::IO_Poll.
Richard Soderberg is <poe@crystalflame.net>, aka "coral". Richard is a collaborator on several side projects involving POE. His work provides valuable testing and feedback from a user's point of view.
Dennis Taylor is <dennis@funkplanet.com>. Dennis has been testing,debugging and patching bits here and there, such as Filter::Line whichhe improved by leaps in 0.1102. He's also the author ofPOE::Component::IRC, the widely popular POE-based successor to hiswildly popular Net::IRC library.
David Davis, aka Xantus is <xantus@cpan.org>. David contributed patchesto the HTTPD filter, and added CALLER_STATE to POE::Session. He is theauthor of Sprocket, a networking framework built on POE.
Please contact the author if you've been forgotten and would like tobe included here.

Author

Rocco Caputo is <rcaputo@cpan.org>. POE is his brainchild. He wishesto thank you for your interest, and he has more thanks than he cancount for all the people who have contributed. POE would not benearly as cool without you.

Except where otherwise noted, POE is Copyright 1998-2013 Rocco Caputo.All rights reserved. POE is free software; you may redistribute itand/or modify it under the same terms as Perl itself.

Thank you for reading!

2022-03-25 perl v5.34.0