1 16 17 package socket.io; 18 19 import java.io.DataOutputStream ; 20 import java.io.FilterOutputStream ; 21 import java.io.IOException ; 22 import java.io.OutputStream ; 23 24 53 public class WrappedOutputStream 54 extends FilterOutputStream { 55 56 60 61 public static final int DEFAULT_BUFFER_SIZE = 1024; 62 63 67 68 protected byte[] fBuffer; 69 70 71 protected int fPosition; 72 73 81 protected DataOutputStream fDataOutputStream; 82 83 87 88 public WrappedOutputStream(OutputStream stream) { 89 this(stream, DEFAULT_BUFFER_SIZE); 90 } 92 96 public WrappedOutputStream(OutputStream stream, int bufferSize) { 97 super(stream); 98 fBuffer = new byte[bufferSize]; 99 fDataOutputStream = new DataOutputStream (stream); 100 } 102 106 112 public void write(int b) throws IOException { 113 fBuffer[fPosition++] = (byte)b; 114 if (fPosition == fBuffer.length) { 115 fPosition = 0; 116 fDataOutputStream.writeInt(fBuffer.length); 117 super.out.write(fBuffer, 0, fBuffer.length); 118 } 119 } 121 122 public void write(byte[] b, int offset, int length) 123 throws IOException { 124 125 if (fPosition > 0) { 127 flush0(); 128 } 129 130 fDataOutputStream.writeInt(length); 132 super.out.write(b, offset, length); 133 134 } 136 140 public void flush() throws IOException { 141 flush0(); 142 super.out.flush(); 143 } 145 153 public void close() throws IOException { 154 flush0(); 155 fDataOutputStream.writeInt(0); 156 super.out.flush(); 157 } 159 163 169 public void flush0() throws IOException { 170 int length = fPosition; 171 fPosition = 0; 172 if (length > 0) { 173 fDataOutputStream.writeInt(length); 174 super.out.write(fBuffer, 0, length); 175 } 176 } 178 } | Popular Tags |