Skip to content

Instantly share code, notes, and snippets.

@ugexe
Last active December 24, 2015 10:38
Show Gist options
  • Save ugexe/6785133 to your computer and use it in GitHub Desktop.
Save ugexe/6785133 to your computer and use it in GitHub Desktop.
perl6 async/thread socket load test client/echo server
sub MAIN( Str :$host = '127.0.0.1', Int :$port!, Int :$connections!, Bool :$os_threads? ) {
my %threads;
(1..$connections).map(-> $count {
my $makesock = {
my $client = IO::Socket::INET.new( host => $host, port => $port );
$client.send($count);
say "count: $count | returned: " ~ $client.recv;
};
%threads{$count} = $os_threads??Thread.start($makesock)!!(async $makesock);
});
$os_threads??(.join for %threads.values)!!(await %threads.values);
say 'All '
~ ($os_threads??'threads'!!'asyncs')
~ ' finished';
}
class echo {
has %.opts is readonly = (
port => 9001,
host => '127.0.0.1',
middlewares => (),
max_concurrency => 40,
);
has Bool $.open is readonly = False;
has IO::Socket::INET $!server;
method start {
$!server = IO::Socket::INET.new(
:localhost(%.opts<host>),
:localport(%.opts<port>),
:listen,
);
$!open = True;
my $cnt = 0;
async {
loop {
my $conn = $!server.accept;
say 'Got connection!';
try {
my $req = $conn.recv;
say "got $req";
$conn.send($req);
say "\tsending $req";
CATCH { default {
try { $conn.close; CATCH { default { } } };
} };
};
}
};
};
};
my $s = echo.new;
$s.start;
say 'listening..' if $s.open;
while $s.open { };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment