如何在Perl中向Websocket的连接客户端发送周期性消息



这个问题类似于Python的这个问题:WebSocket服务器在python中定期发送消息

在Perl中创建WebSocket的例子使用了一个小的消息发送服务:http://search.cpan.org/黄玉/净- websocket服务器- 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客户机,然后由服务器广播出去?

升级到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;

我找到了一个简单的解决方法,尽管我不确定它是否是最好的解决方案。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!!");
            }
        },
            );
    },
    );

相关内容

  • 没有找到相关文章