Perl POE - 如何正确地产生计时器

时间:2013-01-22 19:21:50

标签: perl timer poe

我正试图在perl中与POE相处。我开始很慢地掌握它的概念,但我真的很难理解它:

#!perl

use warnings;
use strict;

use IO::Socket;
use POE qw(Wheel::SocketFactory Wheel::ReadWrite);

my $SERVER_ADDR = '192.168.178.6';
my $SERVER_PORT = '50099';


POE::Session->create(
    inline_states => {
        _start => sub {
            # Start the server.
            $_[HEAP]{server} = POE::Wheel::SocketFactory->new(
                RemoteAddress  => $SERVER_ADDR,
                RemotePort     => $SERVER_PORT,
                SocketProtocol => 'udp',
                SuccessEvent   => "on_connect",
                FailureEvent   => "on_server_error",
            );
        },
        on_connect => sub {
            # Begin interacting with the server.
            my $client_socket = $_[ARG0];
            my $io_wheel      = POE::Wheel::ReadWrite->new(
                Handle     => $client_socket,
                InputEvent => "on_recieve_data",
                ErrorEvent => "on_connect_error",
            );
            $_[HEAP]{client}{ $io_wheel->ID() } = $io_wheel;

            $io_wheel->put( "login monitor monitor", "log on", );
        },

        on_server_error => sub {
            # Shut down server.
            my ( $operation, $errnum, $errstr ) = @_[ ARG0, ARG1, ARG2 ];
            warn "Server $operation error $errnum: $errstr\n";
            delete $_[HEAP]{server};
        },
        on_recieve_data => sub {
            # Handle client input.
            my ( $kernel, $input, $wheel_id ) = @_[ KERNEL, ARG0, ARG1 ];
            print "Received: $input\n";

            $kernel->yield('keepalive');
        },
        on_connect_error => sub {
            # Handle client error, including disconnect.
            my $wheel_id = $_[ARG3];
            delete $_[HEAP]{client}{$wheel_id};
        },
        keepalive => sub {
            my ( $kernel, $input, $wheel_id, $io_wheel ) = @_[ KERNEL, ARG0, ARG1, ARG2 ];
            $kernel->delay_add( keepalive => 10 );
            $io_wheel->put( "keepalive" );
        },
    }
);

POE::Kernel->run();
exit;

使用此代码,我将连接到UDP服务器应用程序并读取其状态消息。除了

之外,它可以使用Sofar
        keepalive => sub { ...

我正在尝试添加一个每隔10秒发送一次keepalive包的计时器。

如何正确设置这样的计时器以及调用它的最佳位置? 我想我搞砸了ReadWrite轮的后面参考,但轮子/事件之间的这种连接仍然是我努力奋斗的东西。 非常感谢您对此的任何帮助和见解。

0 个答案:

没有答案