01: // SocketOutputBuffer.java
02: // $Id: SocketOutputBuffer.java,v 1.4 2000/08/16 21:37:42 ylafon Exp $
03: // (c) COPYRIGHT MIT and INRIA, 1996.
04: // Please first read the full copyright statement in file COPYRIGHT.html
05:
06: package org.w3c.jigsaw.http.socket;
07:
08: import java.io.FilterOutputStream;
09: import java.io.IOException;
10: import java.io.OutputStream;
11:
12: /**
13: * A very specific class to buffer output sent back to the client.
14: * None of the Java base class are adequat, in particular,
15: * BufferedOutputStream has to inconvenient:
16: * <ul>
17: * <li>It enforces buffer reallocation on each new connection.
18: * <li>It is not very smart with flushing the stream (it flushes it whenever
19: * output exceeds buffer size, which triggers a reply header flush before
20: * any data bytes can be added to the packet).
21: */
22:
23: class SocketOutputBuffer extends FilterOutputStream {
24: protected byte buf[] = null;
25: protected int count = 0;
26:
27: public void close() throws IOException {
28: try {
29: try {
30: flush();
31: } catch (Exception ex) {
32: }
33: try {
34: out.close();
35: } catch (Exception ex) {
36: }
37: } finally {
38: out = null;
39: count = 0;
40: }
41: }
42:
43: public void flush() throws IOException {
44: if (count > 0) {
45: out.write(buf, 0, count);
46: count = 0;
47: }
48: }
49:
50: public void write(byte b[]) throws IOException {
51: write(b, 0, b.length);
52: }
53:
54: public void write(byte b[], int off, int len) throws IOException {
55: int avail = buf.length - count;
56: if (len < avail) {
57: System.arraycopy(b, off, buf, count, len);
58: count += len;
59: return;
60: } else if ((avail > 0) && (count > 0)) {
61: System.arraycopy(b, off, buf, count, avail);
62: count += avail;
63: flush();
64: out.write(b, off + avail, len - avail);
65: } else {
66: flush();
67: out.write(b, off, len);
68: }
69: }
70:
71: public void write(int b) throws IOException {
72: if (count == buf.length)
73: flush();
74: buf[count++] = (byte) b;
75: }
76:
77: public void reuse(OutputStream out) {
78: this .out = out;
79: this .count = 0;
80: }
81:
82: public SocketOutputBuffer(OutputStream out) {
83: this (out, 512);
84: }
85:
86: public SocketOutputBuffer(OutputStream out, int size) {
87: super (out);
88: this .buf = new byte[size];
89: this .count = 0;
90: }
91: }
|