Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add IO::Socket initial implementation. Patch courtesy of Cosimo Strep…
…pone.
- Loading branch information
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
#!/usr/bin/perl6 | ||
|
||
class IO::Socket { | ||
|
||
has $!PIO; | ||
|
||
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 | ||
$P0 = find_lex "$hostname" | ||
hostname = $P0 | ||
$P0 = find_lex "$port" | ||
port = $P0 | ||
# Create the socket handle | ||
sock = new '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 recv () { | ||
fail('Socket not available') unless $!PIO; | ||
my $received = $!PIO.recv(); | ||
my $len = $received.chars; | ||
my $buf; | ||
while $len > 0 { | ||
$buf = $!PIO.recv(); | ||
$received ~= $buf; | ||
$len = $buf.chars; | ||
} | ||
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(); | ||
} | ||
|
||
} | ||
|