1
2
3
4
5 package org.neo.swarm.util.io;
6
7 import java.io.IOException;
8 import java.io.OutputStream;
9
10 /***
11 * Provides a custom packet protocol as defined in the PacketInputStream.
12 * Note: Alternative implementations of the these streams could be written
13 * to handle different wire protocol such as SOAP or HTTP.
14 * @see org.neo.swarm.util.io.PacketInputStream
15 * @author navery
16 */
17 public class PacketOutputStream extends OutputStream {
18
19 OutputStream parent;
20
21 public PacketOutputStream(OutputStream parent) {
22 this.parent = parent;
23 }
24
25
26
27
28 public void write(int arg0) throws IOException {
29 throw new IOException("use write(byte[]) instead..");
30 }
31
32
33
34
35 public void write(byte[] data) throws IOException {
36 parent.write(PacketInputStream.START_DATA);
37 parent.write(toBytes(data.length));
38 parent.write(data);
39 parent.write(PacketInputStream.END_DATA);
40 }
41
42
43
44
45 public void flush() throws IOException {
46 parent.flush();
47 }
48
49
50
51 public void close() throws IOException {
52 parent.close();
53 }
54 /***
55 * Converts an integer to four bytes
56 * @param n - the integer
57 * @return - four bytes in an array
58 */
59 public static byte[] toBytes(int n) {
60 byte[] b = new byte[4];
61 b[3] = (byte) (n);
62 n >>>= 8;
63 b[2] = (byte) (n);
64 n >>>= 8;
65 b[1] = (byte) (n);
66 n >>>= 8;
67 b[0] = (byte) (n);
68 return b;
69 }
70 }