我有一个在Linux上运行的服务器端websocket,最后websocket正在运行但是在app-> start之后需要执行更多; 就像在下面的代码中一样,我放了一个打印hello世界来尝试它,但它确实不起作用。 有人知道如何处理这个问题吗?
#!/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";
答案 0 :(得分:3)
简短的回答是app-&gt; start永远不会返回。 app-&gt; start之前的代码为您定义的路径创建处理程序。当服务器获取其中一条路由的请求时,它会使用您提供的处理程序之一来生成服务器返回的内容。您可能会发现阅读有关事件驱动编程的内容很有帮助。路线可以被视为您的程序正在处理的事件。 app-&gt;启动或多或少意味着&#34;启动事件循环&#34;。