这个问题类似于Python的这个问题: WebSocket Server sending messages periodically in python
在Perl中创建WebSocket的示例使用了一个小消息发送服务: http://search.cpan.org/~topaz/Net-WebSocket-Server-0.001003/lib/Net/WebSocket/Server.pm
代码是:
use Net::WebSocket::Server;
my $origin = 'http://example.com';
Net::WebSocket::Server->new(
listen => 8080,
on_connect => sub {
my ($serv, $conn) = @_;
$conn->on(
handshake => sub {
my ($conn, $handshake) = @_;
$conn->disconnect() unless $handshake->req->origin eq $origin;
},
utf8 => sub {
my ($conn, $msg) = @_;
$_->send_utf8($msg) for $conn->server->connections;
},
binary => sub {
my ($conn, $msg) = @_;
$_->send_binary($msg) for $conn->server->connections;
},
);
},
)->start;
此示例基于事件,仅根据客户端发送的消息向客户端发送消息。如果我想向所有连接的客户端发送定期消息,那么这样做的好方法是什么?我是否可以创建在套接字服务器中触发的定期事件,或者是否有办法创建连接到服务器并发送消息的Perl客户端,然后服务器将其广播出去?
答案 0 :(得分:3)
升级到Net::WebSocket::Server v0.3.0,它通过“tick_period”参数和“tick”事件内置了此功能。见下面的例子:
use Net::WebSocket::Server;
my $ws = Net::WebSocket::Server->new(
listen => 8080,
tick_period => 1,
on_tick => sub {
my ($serv) = @_;
$_->send_utf8(time) for $serv->connections;
},
)->start;
答案 1 :(得分:0)
我找到了一个简单的解决方法,虽然我不确定它是否是最好的解决方案。 Websocket服务器可以触发的事件之一是on_pong
。此外,如果在创建Websocket服务器时设置silence_max
,它会定期ping所有客户端,等待pong响应。然后可以使用此pong向所有客户端触发消息。代码如下:
my $server = Net::WebSocket::Server->new(
listen => 2222,
silence_max => 5, # Send a ping to cause a client pong ever 5 seconds
on_connect => sub {
my ($serv, $conn) = @_;
$conn->on(
handshake => sub {
my ($conn, $handshake) = @_;
print $handshake->req->origin."\n";
$conn->disconnect() unless $handshake->req->origin eq $origin;
},
utf8 => sub {
my ($conn, $msg) = @_;
my $num_connections = scalar $conn->server->connections;
foreach my $connection ($conn->server->connections) {
if ($conn != $connection) {
$connection->send_utf8("$num_connections connected: ".$msg);
}
}
},
pong => sub {
foreach my $connection ($conn->server->connections) {
$connection->send_utf8("Broadcast message!!");
}
},
);
},
);