Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class IO2::Socket::INET
- {
- has $!PIO;
- method pio()
- {
- $!PIO;
- }
- method open (Str $hostname, Int $port)
- {
- my $s = 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']
- $P1 = new 'Integer'
- 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)
- $P1 = sock.'connect'(address)
- setattribute self, '$!PIO', sock
- goto DONE
- ERR:
- $P1 = -1
- DONE:
- %r = $P1
- };
- }
- multi method write(Str $str) {
- fail("Not connected") unless $!PIO;
- return $!PIO.send($str);
- }
- multi method write(Buf $buf) {
- fail("Not connected") unless $!PIO;
- my @contents = $buf.contents;
- my $pio = $!PIO;
- Q:PIR {
- $P0 = find_lex '@contents'
- .local pmc bb
- .local string s
- bb = new ['ByteBuffer']
- .local pmc it
- .local int i
- it = iter $P0
- i = 0
- loop:
- unless it goto done
- $P1 = shift it
- $I1 = $P1
- bb[i] = $I1
- inc i
- goto loop
- done:
- s = bb.'get_string_as'(binary:"")
- .local pmc pio
- pio = find_lex '$pio'
- pio = deref_unless_object pio
- pio.'send'(s)
- };
- }
- method read(Int $bytes) {
- my $pio = $!PIO;
- my @bytes = Q:PIR {
- .local int nbytes, byte
- .local pmc bytebuffer, it, result
- .local pmc pio
- pio = find_lex '$pio'
- pio = deref_unless_object pio
- $P0 = find_lex '$bytes'
- nbytes = $P0
- $S0 = pio.'recv'(nbytes)
- bytebuffer = new ['ByteBuffer']
- bytebuffer = $S0
- result = new ['Parcel']
- it = iter bytebuffer
- bytes_loop:
- unless it goto done
- byte = shift it
- push result, byte
- goto bytes_loop
- done:
- %r = result
- };
- return Buf.new(@bytes);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement