-
-
Save kanatohodets/8ffb1a18ff04c80225cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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