Search code examples
perlnetwork-programmingpoe

Are multiple simultaneous Perl POE providers permitted?


I'm using POE to build a system that bridges several protocols (HTTP, IRC, XMPP), and I'd like to use POE to drive a single event loop that handles these protocols. Can I do this safely, and if so, how?


Solution

  • Yes, you can. Read this article, it should help you much. Also here's code example of IRC and HTTP running together: Just remember, you need setup everything before you run mainloop: POE::Kernel->run()

    #!/usr/bin/env perl
    use warnings;
    use strict;
    use POE;
    
    # Simple HTTP server
    
    use POE::Component::Server::HTTP;
    
    POE::Component::Server::HTTP->new(
      Port           => 32090,
      ContentHandler => {
        '/'      => \&http_handler
      }
    );
    
    sub http_handler {
        my ($request, $response) = @_;
        $response->code(RC_OK);
        $response->content("<html><body>Hello World</body></html>");
        return RC_OK;
    }
    
    # Dummy IRC bot on #bottest at irc.perl.org
    
    use POE::Component::IRC;
    
    my ($irc) = POE::Component::IRC->spawn();
    
    POE::Session->create(
      inline_states => {
        _start     => \&bot_start,
        irc_001    => \&on_connect,
      },
    );
    
    sub bot_start {
      $irc->yield(register => "all");
      my $nick = 'poetest' . $$ % 1000;
      $irc->yield(
        connect => {
          Nick     => $nick,
          Username => 'cookbot',
          Ircname  => 'POE::Component::IRC cookbook bot',
          Server   => 'irc.perl.org',
          Port     => '6667',
        }
      );
    }
    
    sub on_connect { $irc->yield(join => '#bottest'); }
    
    
    # Run main loop
    
    POE::Kernel->run();
    

    And you can broadcast events between your tasks.