我正在尝试在 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 服务器应用程序并读取其状态消息。到目前为止,它的工作原理是
keepalive => sub { ...
我正在尝试添加一个计时器,该计时器每 10 秒发送一次 keepalive 包。
如何正确设置这样的计时器以及调用它的最佳位置是什么?我想我弄乱了对 ReadWrite 轮的反向引用,但是轮/事件等之间的这种联系仍然是我正在努力解决的问题。非常感谢您对此的任何帮助和见解。