Skip to content

Commit

Permalink
Add back IO::Socket and IO::Socket::INET with the small tweak needed …
Browse files Browse the repository at this point in the history
…for ng, as pointed out by ash++.
  • Loading branch information
jnthn committed Mar 24, 2010
1 parent 6adcf14 commit d0bf6e3
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
2 changes: 2 additions & 0 deletions build/Makefile.in
Expand Up @@ -190,6 +190,8 @@ CORE_SOURCES = \
src/core/Hash.pm \
src/core/Enum.pm \
src/core/IO.pm \
src/core/IO/Socket.pm \
src/core/IO/Socket/INET.pm \
src/core/Parameter.pm \
src/core/Signature.pm \
src/core/Block.pm \
Expand Down
34 changes: 34 additions & 0 deletions src/core/IO/Socket.pm
@@ -0,0 +1,34 @@
use v6;

role IO::Socket {
has $!PIO;
has $!buffer = '';

method recv (Int $bufsize = Inf) {
fail('Socket not available') unless $!PIO;
my $received;
while $bufsize > $!buffer.bytes {
$received = $!PIO.recv();
last unless $received.chars;
$!buffer ~= $received;
}
if $bufsize == Inf {
$received = $!buffer;
$!buffer = '';
} else {
$received = $!buffer.substr(0, $bufsize);
$!buffer .= substr($bufsize);
}
return $received;
}

method send (Str $string) {
fail("Not connected") unless $!PIO;
return $!PIO.send($string);
}

method close () {
fail("Not connected!") unless $!PIO;
return $!PIO.close();
}
}
56 changes: 56 additions & 0 deletions src/core/IO/Socket/INET.pm
@@ -0,0 +1,56 @@
class IO::Socket::INET does IO::Socket {

method open (Str $hostname, Int $port) {

Q:PIR {
.include "socket.pasm"
.local pmc sock
.local pmc address
.local string hostname
.local int port
.local string buf
.local int ret
.local pmc self
self = find_lex 'self'
$P0 = find_lex "$hostname"
hostname = $P0
$P0 = find_lex "$port"
port = $P0
# Create the socket handle
sock = root_new ['parrot';'Socket']
unless sock goto ERR
sock.'socket'(.PIO_PF_INET, .PIO_SOCK_STREAM, .PIO_PROTO_TCP)
# Pack a sockaddr_in structure with IP and port
address = sock.'sockaddr'(hostname, port)
sock.'connect'(address)
setattribute self, '$!PIO', sock
ERR:
.return (0)
}
}

method socket(Int $domain, Int $type, Int $protocol) {
my $PIO := Q:PIR {{ %r = root_new ['parrot';'Socket'] }};
$PIO.socket($domain, $type, $protocol);
return IO::Socket::INET.new( :PIO($PIO) );
}

method bind($host, $port) {
$!PIO.bind($!PIO.sockaddr($host, $port));
return self;
}

method listen() {
$!PIO.listen(1);
return self;
}

method accept() {
return $!PIO.accept();
}
}

0 comments on commit d0bf6e3

Please sign in to comment.