Skip to content

Instantly share code, notes, and snippets.

@kanatohodets
Last active September 4, 2015 14:32
Show Gist options
  • Save kanatohodets/8ffb1a18ff04c80225cc to your computer and use it in GitHub Desktop.
Save kanatohodets/8ffb1a18ff04c80225cc to your computer and use it in GitHub Desktop.
use v6;
my @clients;
my $max_id = 0;
react {
whenever IO::Socket::Async.listen('localhost', 3005) -> $sock {
my $id = $max_id++;
$sock.print("Hi! You are $id.\n");
@clients>>.print("* $id connected\n");
# aka: $_.print('stuff') for @clients
@clients.push($sock);
whenever $sock.chars-supply -> $bytes {
@clients>>.print("{$id}: $bytes");
LAST {
@clients .= grep({ $_ !eqv $sock });
@clients>>.print("* $id disconnected\n");
}
}
}
}
my (@broadcast, %handlers);
while (1) {
for my $sock ($select->can_read(1)) {
if ($sock == $listen) {
my $new = $listen->accept;
$select->add($new);
$handlers{$new->fileno} = {
on_read => sub ($data) { push @broadcast, $new->fileno . ": $data" }
};
push @broadcast, sprintf("* %s connected\n", $new->fileno);
} else {
if ($sock->sysread(my $buffer, 4096, 0)) {
$handlers{$sock->fileno}->{on_read}->($buffer);
} else {
push @broadcast, sprintf("* %s disconnected\n", $sock->fileno);
$select->remove($sock) and $sock->close;
}
}
}
if (my @writable = $select->can_write(1)) {
if (my $message = shift @broadcast) {
$_->print($message) for @writable;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment