1 package com.quadcap.net.server; 2 3 40 41 import java.io.FileOutputStream ; 42 import java.io.IOException ; 43 import java.io.OutputStream ; 44 45 import com.quadcap.util.Debug; 46 47 55 public final class WorkerOutputStream extends OutputStream { 56 static final int MAX = 4096; 57 byte[] buf = new byte[MAX]; 58 byte[] temp = new byte[16]; 59 int pos = 0; 60 OutputStream out; 61 62 static boolean doTrace = false; 64 FileOutputStream log; 65 67 public WorkerOutputStream(FileOutputStream log) { 68 doTrace = (log != null); 70 this.log = log; 71 } 73 74 public final void reset(OutputStream out) throws IOException { 75 this.out = out; 76 this.pos = 0; 77 if (doTrace) { 79 log.write(("RESET " + Thread.currentThread().getName() + 80 "\r\n").getBytes()); 81 } 82 } 84 85 public final void write(int c) throws IOException { 86 if (pos >= MAX) { 87 owrite(buf, 0, MAX); 88 } 89 buf[pos++] = (byte)c; 90 } 91 92 final void owrite(byte[] b, int off, int len) throws IOException { 93 out.write(b, off, len); 94 pos = 0; 95 if (doTrace) { 97 log.write("WRITE\r\n".getBytes()); 98 log.write(b, off, len); 99 } 100 } 102 103 public final void write(String s) throws IOException { 104 int len = s.length(); 105 int off = 0; 106 while (len + pos >= MAX) { 107 int slen = MAX - pos; 108 s.getBytes(off, off + slen, buf, pos); 109 owrite(buf, 0, MAX); 110 off += slen; 111 len -= slen; 112 pos = 0; 113 } 114 if (len > 0) { 115 s.getBytes(off, len, buf, pos); 116 pos += len; 117 } 118 } 119 120 public final void write(byte[] b, int off, int len) throws IOException { 121 final int npos = pos + len; 122 if (npos >= MAX) { 123 if (pos == 0) { 124 owrite(b, off, len); 125 } else { 126 final int slen = MAX - pos; 127 System.arraycopy(b, off, buf, pos, slen); 128 owrite(buf, 0, MAX); 129 len -= slen; 130 if (len < MAX) { 131 System.arraycopy(b, off + slen, buf, 0, len); 132 pos = len; 133 } else { 134 pos = 0; 135 owrite(b, off + slen, len); 136 } 137 } 138 } else { 139 System.arraycopy(b, off, buf, pos, len); 140 pos = npos; 141 } 142 } 143 144 public final void write(byte[] b) throws IOException { 145 write(b, 0, b.length); 146 } 147 148 public final void flush() throws IOException { 149 if (pos > 0) { 150 owrite(buf, 0, pos); 151 pos = 0; 152 } 153 out.flush(); 154 } 155 156 static final byte[] digits = "0123456789".getBytes(); 157 158 public final void writeInt(int x) throws IOException { 159 int p = 0; 160 while (x > 0) { 161 temp[p++] = digits[x % 10]; 162 x /= 10; 163 } 164 if (p == 0) temp[p++] = (byte)'0'; 165 if (pos + p < MAX) { 166 while (p > 0) buf[pos++] = temp[--p]; 167 } else { 168 while (p > 0) write(temp[--p]); 169 } 170 } 171 172 public final void close() throws IOException { 173 flush(); 174 out.close(); 175 if (doTrace) log.write("CLOSE\r\n".getBytes()); 177 } 179 } 180 | Popular Tags |