1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package net.sf.magicproject.network;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24
25 /***
26 * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a>
27 */
28 class VirtualInputStream extends InputStream {
29
30 private static final int MAX_SIZE = 300;
31
32 /***
33 * As standard read method, if buffer is empty, current thread would be
34 * blocked until bytes would be available
35 *
36 * @return the next available byte
37 * @throws IOException
38 * never throwsn, but inheritence constraint the presence of this
39 * tag
40 * @see java.io.InputStream#read()
41 */
42 @Override
43 public synchronized int read() throws IOException {
44 if (disconnected) {
45 throw new IOException("disconnected");
46 }
47 try {
48 while (pointerRead == pointerAdd) {
49 wait(500);
50 }
51 } catch (InterruptedException e) {
52 e.printStackTrace();
53 }
54 if (disconnected) {
55 throw new IOException("disconnected");
56 }
57 return buffer[pointerRead++ % MAX_SIZE];
58 }
59
60 /***
61 * Update the buffer with the next message read from the given input stram.
62 *
63 * @param in
64 * the input stream containing the message to read.
65 * @throws IOException
66 * If some other I/O error occurs
67 */
68 synchronized void newMessage(InputStream in) throws IOException {
69 int size = in.read();
70 while (size-- > 0) {
71 buffer[pointerAdd++ % MAX_SIZE] = in.read();
72 }
73 notify();
74 }
75
76 @Override
77 public synchronized void reset() {
78 pointerAdd++;
79 disconnected = true;
80 notify();
81 }
82
83 private boolean disconnected = false;
84
85 private int[] buffer = new int[MAX_SIZE];
86
87 private int pointerAdd = 0;
88
89 private int pointerRead = 0;
90
91 }