summaryrefslogtreecommitdiff
path: root/java-plan1/test.java
blob: 5b2349fdcf49ecfd7f66dd8643f83893349b7bc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.*;
import java.io.*;

class OpenByteArrayOutputStream extends ByteArrayOutputStream {
	int getCount() { return count; }
	byte[] getBuffer() { return buf; }
}


public class test {

	public static void main(String[] args) throws IOException
	{
		testSimple();
		testStreaming();
	}


	public static void testSimple() throws IOException
	{
		OpenByteArrayOutputStream out = new OpenByteArrayOutputStream();

		Packer pk = new Packer(out);
		pk.packArray(3)
			.packInt(1)
			.packByte((byte)2)
			.packDouble(0.3);

		Unpacker pac = new Unpacker();
		int nlen = pac.execute(out.getBuffer(), 0, out.getCount());

		if(pac.isFinished()) {
			System.out.println("testSimple: "+pac.getData());
		}
	}


	public static void testStreaming() throws IOException
	{
		OpenByteArrayOutputStream out = new OpenByteArrayOutputStream();

		////
		// sender
		//
		// initialize the streaming serializer
		Packer pk = new Packer(out);

		// serialize 2 objects
		pk.packArray(3)
			.packInt(0)
			.packByte((byte)1)
			.packDouble(0.2);
		pk.packArray(3)
			.packInt(3)
			.packByte((byte)4)
			.packDouble(0.5);

		// send it through the network
		InputStream sock = new ByteArrayInputStream(out.getBuffer(), 0, out.getCount());


		////
		// receiver
		//
		// initialize the streaming deserializer
		Unpacker pac = new Unpacker();
		int parsed = 0;

		byte[] buf = new byte[1024];
		int buflen = 0;

		while(true) {
			// receive data from the network
			int c = sock.read();
			if(c < 0) { return; }

			buf[buflen++] = (byte)c;

			// deserialize
			parsed = pac.execute(buf, parsed, buflen);
			if(pac.isFinished()) {
				// get an object
				Object msg = pac.getData();
				System.out.println("testStreaming: "+msg);

				// reset the streaming deserializer
				pac.reset();
				buflen = 0;
				parsed = 0;
			}
		}
	}
}