Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add basic async client socket support.
Only works on MoarVM so far, missing reading bytes and robustness and
various other bits, but enough for writing a simple async HTTP client.
  • Loading branch information
jnthn committed Apr 20, 2014
1 parent 170241a commit 25e2ff4
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
90 changes: 90 additions & 0 deletions src/core/IO/Socket/Async.pm
@@ -0,0 +1,90 @@
my class IO::Socket::Async {
my class SocketCancellation is repr('AsyncTask') { }

has $!VMIO;

method new() {
die "Cannot create an asynchronous socket directly; please use" ~
"IO::Socket::Async.connect or IO::Socket::Async.listen.";
}

method send(IO::Socket::Async:D: $str as Str, :$scheduler = $*SCHEDULER) {
my $p = Promise.new;
my $v = $p.vow;
nqp::asyncwritestr(
$!VMIO,
$scheduler.queue,
-> Mu \bytes, Mu \err {
if err {
$v.break(err);
}
else {
$v.keep(bytes);
}
},
nqp::unbox_s($str), SocketCancellation);
$p
}

method write(IO::Socket::Async:D: Buf $b, :$scheduler = $*SCHEDULER) {
my $p = Promise.new;
my $v = $p.vow;
nqp::asyncwritebytes(
$!VMIO,
$scheduler.queue,
-> Mu \bytes, Mu \err {
if err {
$v.break(err);
}
else {
$v.keep(bytes);
}
},
nqp::decont($b), SocketCancellation);
$p
}

method chars_supply(IO::Socket::Async:D: :$scheduler = $*SCHEDULER) {
my $s = Supply.new;
nqp::asyncreadchars(
$!VMIO,
$scheduler.queue,
-> Mu \seq, Mu \data, Mu \err {
if err {
$s.quit(err);
}
elsif seq < 0 {
$s.done();
}
else {
$s.more(data);
}
},
SocketCancellation);
$s
}

method close(IO::Socket::Async:D:) {
nqp::closefh($!VMIO);
}

method connect(IO::Socket::Async:U: $host as Str, $port as Int,
:$scheduler = $*SCHEDULER) {
my $p = Promise.new;
my $v = $p.vow;
nqp::asyncconnect(
$scheduler.queue,
-> Mu \socket, Mu \err {
if err {
$v.break(err);
}
else {
my $client_socket := nqp::create(self);
nqp::bindattr($client_socket, IO::Socket::Async, '$!VMIO', socket);
$v.keep($client_socket);
}
},
$host, $port, SocketCancellation);
$p
}
}
1 change: 1 addition & 0 deletions tools/build/Makefile-Moar.in
Expand Up @@ -168,6 +168,7 @@ M_CORE_SOURCES = \
src/core/signals.pm \
src/core/IO/Socket.pm \
src/core/IO/Socket/INET.pm \
src/core/IO/Socket/Async.pm \
src/core/OS.pm \
src/core/core_epilogue.pm \

Expand Down

0 comments on commit 25e2ff4

Please sign in to comment.