diff options
author | Matthias Schiffer <mschiffer@universe-factory.net> | 2010-07-07 05:24:31 +0200 |
---|---|---|
committer | Matthias Schiffer <mschiffer@universe-factory.net> | 2010-07-07 05:24:31 +0200 |
commit | 712b073f95f694f23a070bd43cd0c9e7479142b7 (patch) | |
tree | 82eaa888eac197da5a772f4bb88a1be6b7bdba63 /src/PacketHandler.vala | |
parent | a6a3c416c77d383f00a723ceb4545e89a2334923 (diff) | |
download | eva-712b073f95f694f23a070bd43cd0c9e7479142b7.tar eva-712b073f95f694f23a070bd43cd0c9e7479142b7.zip |
Implemented most types, sending & receiving
Diffstat (limited to 'src/PacketHandler.vala')
-rw-r--r-- | src/PacketHandler.vala | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/src/PacketHandler.vala b/src/PacketHandler.vala new file mode 100644 index 0000000..0f5cd3c --- /dev/null +++ b/src/PacketHandler.vala @@ -0,0 +1,77 @@ +namespace Eva { + public class PacketHandler { + private DataInputStream istream; + private DataOutputStream ostream; + private int sizeLength; + + public signal void received_term(Term term); + + public PacketHandler(InputStream input, OutputStream output, int length) { + assert(length == 1 || length == 2 || length == 4); + + istream = new DataInputStream(input); + ostream = new DataOutputStream(output); + sizeLength = length; + + istream.byte_order = DataStreamByteOrder.BIG_ENDIAN; + ostream.byte_order = DataStreamByteOrder.BIG_ENDIAN; + } + + public void send(Term term) throws Error { + Erl.Buffer buffer = Erl.Buffer.with_version(); + term.encode(buffer); + + switch(sizeLength) { + case 1: + ostream.put_byte((uchar)buffer.buff.length, null); + break; + case 2: + ostream.put_uint16((uint16)buffer.buff.length, null); + break; + case 4: + ostream.put_uint32((uint32)buffer.buff.length, null); + break; + } + + ostream.write(buffer.buff, buffer.buff.length, null); + } + + private async void receive() throws Error { + while(true) { + while(istream.get_available() < sizeLength) { + yield istream.fill_async((ssize_t)(sizeLength - istream.get_available()), 0, null); + } + + int length = 0; + switch(sizeLength) { + case 1: + length = istream.read_byte(null); + break; + case 2: + length = istream.read_uint16(null); + break; + case 4: + length = (int)istream.read_uint32(null); + break; + } + + uint8[] buffer = new uint8[length]; + size_t received = 0; + + while(received < length) { + size_t ret = yield istream.read_async(&(buffer[received]), length-received, 0, null); + assert(ret > 0); + + received += ret; + } + + Term term = Term.decode(buffer); + Idle.add(() => {received_term(term); return false;}); + } + } + + public void start() { + receive.begin(); + } + } +} |