Skip to content

Instantly share code, notes, and snippets.

@kraih
Last active September 15, 2015 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kraih/ac0502106bf0f643ea10 to your computer and use it in GitHub Desktop.
Save kraih/ac0502106bf0f643ea10 to your computer and use it in GitHub Desktop.
#
# Tested on OS X 10.9.2 (MacBook Air) with Perl 5.18.2 and EV 4.17 (kqueue)
#
# 267.0MB memory usage, 0% CPU usage once roundtrips are finished after 29s
# (with all 10k sockets still open)
#
# Get the latest version of Mojolicious from http://github.com/kraih/mojo
# $ sudo sysctl -w kern.maxfiles=40960 kern.maxfilesperproc=20480
# $ ulimit -n 20480
# $ LIBEV_FLAGS=8 perl c10k_client.pl
#
use Mojo::Base -strict;
use Mojo::IOLoop;
use Mojo::UserAgent;
# Client with longer than normal connect and inactivity timeout
my $ua
= Mojo::UserAgent->new(connect_timeout => 300, inactivity_timeout => 300);
# 100 batches of 100 WebSocket connections
my $start = time;
my $timing = Mojo::IOLoop->delay(
sub { say '10k roundtrips finished in ', (time - $start), ' seconds.' });
_batch(100);
# Our event loop will have to handle at least 10k sockets
Mojo::IOLoop->singleton->max_connections(100000)->start;
sub _batch {
return unless my $batch = shift;
say 'Batch: ', $batch--;
my $next = Mojo::IOLoop->delay(sub { _batch($batch) });
for (1 .. 100) {
my $connected = $next->begin;
my $received = $timing->begin;
$ua->websocket('ws://localhost:3000' => sub {
my ($ua, $tx) = @_;
say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
$tx->on(message => $received);
$tx->send('Hello Mojo!');
$connected->();
});
}
}
#
# Tested on OS X 10.9.2 (MacBook Air) with Perl 5.18.2 and EV 4.17 (kqueue)
#
# 272.4MB memory usage, 0% CPU usage once roundtrips are finished after 29s
# (with all 10k sockets still open)
#
# Get the latest version of Mojolicious from http://github.com/kraih/mojo
# $ sudo sysctl -w kern.maxfiles=40960 kern.maxfilesperproc=20480
# $ ulimit -n 20480
# $ LIBEV_FLAGS=8 perl c10k_server.pl
#
use Mojo::Base -strict;
use Mojolicious::Lite;
use Mojo::IOLoop;
use Mojo::Server::Daemon;
# Silence
app->log->level('error');
# Echo incoming WebSocket messages
my $num;
websocket '/' => sub {
my $self = shift;
say 'Opened: ', ++$num;
$self->on(message => sub { shift->send(shift) });
$self->on(finish => sub { say 'Closed: ', --$num });
};
# Our event loop will have to handle at least 10k sockets
Mojo::IOLoop->singleton->max_connections(100000);
# Server with longer than normal inactivity timeout
my $daemon = Mojo::Server::Daemon->new(
silent => 1,
app => app,
inactivity_timeout => 300,
listen => ['http://127.0.0.1:3000']
)->run;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment