perldancer

Is there a way to allow multiple connections to Dancer2


My program:

#!/usr/bin/perl

use strict;
use warnings;
use Dancer2;

$| = 1;

set host => '127.0.0.1';
set port => 7071;

get '/foo' => sub {
    `sleep 5`;
    'ok'
};

start;

Then I am run the following for loop:

for i in $(seq 1 3)
> do
>   time curl http://localhost:7071/foo &
> done

Output:

ok
real    0m5.032s
user    0m0.013s
sys     0m0.000s
ok
real    0m10.037s
user    0m0.012s
sys     0m0.000s
ok
real    0m15.043s
user    0m0.004s
sys     0m0.008s

It seems to Dancer2 can only accept one request one time, how to allow multiple connections to Dancer2?


Solution

  • Perl programs are generally single-threaded. If you want to handle multiple things at the same time, you need to manage that explicitly.

    If you are familiar with the Express web framework in JavaScript, it generally uses the second approach: NodeJS doesn't let you block the process by sleeping, and instead requires you to use promises (async/await) or callbacks to explicitly account for asynchronous execution.