我有一个服务器端websocket在linux上运行,最后websocket正在运行,但是在app->start之后需要执行更多的操作;
就像在下面的代码中,我放了一个打印的hello world来尝试,但它不起作用。
有人知道怎么处理?

    #!/usr/bin/perl
use utf8;
use Mojolicious::Lite;
use DateTime;
use Mojo::JSON;
use Mojo::Transaction::WebSocket;
use Data::Dumper;
no strict "refs";

get '/' => 'index';
my $clients = {};
# Arrays voor het ordenen van gasten
my @hoofdArray =();
my $teller = 0;

websocket '/echo' => sub {
    my $self = shift;
    $self->inactivity_timeout(0);
    app->log->debug(sprintf 'Client connected: %s', $self->tx);
    # Toevoegen origin op array positie
    $teller = $teller + 1;
    # later renderen van de websocket

    # Pushen van alle gasten in een array
    my $id = sprintf "%s", $self->tx;
    $clients->{$id} = $self->tx;
    $self->on(message =>
        sub {

            my ($self, $msg) = @_;

            if (index($msg, "naam:") != -1){
                my $ori = $self->tx->handshake->connection;
                my $naam = substr $msg,5;
                print $naam."\n";

                my @gasten = ();
                push(@gasten, $ori);
                push(@gasten, $naam);
                push(@hoofdArray, \@gasten);
            }
            else {
                my $json = Mojo::JSON->new;
                my $dt   = DateTime->now( time_zone => 'Europe/Amsterdam');
                my $currentNaam = "undefinid";
                for (my $i = 0; $i < @hoofdArray; $i++){

                    if($hoofdArray[$i]->[0] eq $self->tx->handshake->connection){
                        $currentNaam = $hoofdArray[$i]->[1];
                        last;
                    }
                }

                for (keys %$clients) {
                    $clients->{$_}->send(
                        $json->encode({
                            hms  => $currentNaam,
                            text => $msg,
                        })
                    );
                    #print $_[0]->tx->handshake->req->content->headers->origin."\n";
                    #print $_[0]->tx->handshake->connection."\n";

                }
                print Dumper $hoofdArray[0];
                print Dumper $hoofdArray[1];
            }
        }
    );

    $self->on(finish =>
        sub {
            app->log->debug('Client with hash: '.$clients->{$id}.' disconnected');
            delete $clients->{$id};
        }
    );
};

app->start;
print "Hello World! \n";

最佳答案

简而言之,app->start永远不会返回。app->start前面的代码为您定义的路由创建处理程序。当服务器收到其中一个路由的请求时,它使用您提供的处理程序之一生成服务器返回的内容。您可能会发现阅读一些关于事件驱动编程的知识是有帮助的。路由可以看作是程序正在处理的事件。app->start或多或少意味着“启动事件循环”。

关于linux - 应用程序->启动后如何处理;在Mojolicious websocket for Perl中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25564844/

10-16 11:45
查看更多