我是Perl初学者,目前正在学习websocket。经过大量的阅读、尝试和复制粘贴,我终于让这段代码工作了:
use strict;
use warnings;
use utf8;
use Data::Dumper;
use IO::Async::Loop;
use IO::Async::Timer::Periodic;
use Net::Async::WebSocket::Client;
use Protocol::WebSocket::URL;
my ($url, $msg, $last_update);
$url = 'ws://127.0.0.1/stream';
$msg = 'get_lists';
my $uri = Protocol::WebSocket::URL->new->parse($url);
my $loop = IO::Async::Loop->new;
my $client = Net::Async::WebSocket::Client->new(
on_frame => sub {
my ($self, $frame) = @_;
chomp($frame);
$last_update = time(); # use this in timer below
# do something else
}
);
$loop->add($client);
$client->connect(
host => $uri->host,
service => $uri->port,
url => $url,
on_connected => sub {
warn "Connection established";
if ($msg) {
$client->send_frame("$msg\n");
}
},
on_connect_error=> sub { die "CONNECT: ".Dumper \@_; },
on_resolve_error=> sub { die "RESOLVE: ".Dumper \@_; },
on_fail => sub { die "FAIL: ".Dumper \@_; },
on_read_eof => sub {
$loop->remove($client);
# reconnect?
}
);
# is the connection to socket is still open?
# check every 30 seconds if $last_update was not updated
my $timer = IO::Async::Timer::Periodic->new(
interval=> 30,
on_tick => sub {
if (!$last_update || time()-30 > $last_update) {
warn "Connection probably dead. No new data for 20 seconds.";
## check connection
## and reconnect if needed
}
},
);
$timer->start;
$loop->add($timer);
$loop->loop_forever;
我还需要解决一件事,但我不确定该如何解决:
我找到了一些类似https://dev59.com/6mfWa4cB1Zd3GeqPipps#12091867的信息,但我不明白如何在我的代码中使用SO_KEEPALIVE。我可能应该自己创建一个IO::Socket连接,并以某种方式将其传递给Async::Net::WebSocket,但我无法做到这一点。实际上,我真的不知道该如何做。显然是初学者的问题。
我尝试使用定时器的第二种方法,它应该每30秒检查一次连接是否打开(如果没有新数据通过套接字传输)。同样的问题,但从另一方面来看:不确定如何使用上述代码检查连接是否打开。
我可以创建一个基本的IO::Socket连接,但我想以某种方式使用上述代码,因为我喜欢Net::Async::WebSocket如何使用事件(on_read-eof、on_frame等)。