()
| 218 | |
| 219 | |
| 220 | @Override |
| 221 | public void run() { |
| 222 | byte[] readBuffer; |
| 223 | { // make the read buffer same size as socket receive buffer so that |
| 224 | // we don't waste cycles calling listeners when there is more data waiting |
| 225 | int readBufferSize = 1 << 16; // 64 KB (default socket receive buffer size) |
| 226 | try { |
| 227 | readBufferSize = socket.getReceiveBufferSize(); |
| 228 | } catch (SocketException ignore) { } |
| 229 | readBuffer = new byte[readBufferSize]; |
| 230 | } |
| 231 | while (Thread.currentThread() == thread) { |
| 232 | try { |
| 233 | while (input != null) { |
| 234 | int readCount; |
| 235 | |
| 236 | // try to read a byte using a blocking read. |
| 237 | // An exception will occur when the sketch is exits. |
| 238 | try { |
| 239 | readCount = input.read(readBuffer, 0, readBuffer.length); |
| 240 | } catch (SocketException e) { |
| 241 | System.err.println("Client SocketException: " + e.getMessage()); |
| 242 | // the socket had a problem reading so don't try to read from it again. |
| 243 | stop(); |
| 244 | return; |
| 245 | } |
| 246 | |
| 247 | // read returns -1 if end-of-stream occurs (for example if the host disappears) |
| 248 | if (readCount == -1) { |
| 249 | System.err.println("Client got end-of-stream."); |
| 250 | stop(); |
| 251 | return; |
| 252 | } |
| 253 | |
| 254 | synchronized (bufferLock) { |
| 255 | int freeBack = buffer.length - bufferLast; |
| 256 | if (readCount > freeBack) { |
| 257 | // not enough space at the back |
| 258 | int bufferLength = bufferLast - bufferIndex; |
| 259 | byte[] targetBuffer = buffer; |
| 260 | if (bufferLength + readCount > buffer.length) { |
| 261 | // can't fit even after compacting, resize the buffer |
| 262 | // find the next power of two which can fit everything in |
| 263 | int newSize = Integer.highestOneBit(bufferLength + readCount - 1) << 1; |
| 264 | if (newSize > MAX_BUFFER_SIZE) { |
| 265 | // buffer is full because client is not reading (fast enough) |
| 266 | System.err.println("Client: can't receive more data, buffer is full. " + |
| 267 | "Make sure you read the data from the client."); |
| 268 | stop(); |
| 269 | return; |
| 270 | } |
| 271 | targetBuffer = new byte[newSize]; |
| 272 | } |
| 273 | // compact the buffer (either in-place or into the new bigger buffer) |
| 274 | System.arraycopy(buffer, bufferIndex, targetBuffer, 0, bufferLength); |
| 275 | bufferLast -= bufferIndex; |
| 276 | bufferIndex = 0; |
| 277 | buffer = targetBuffer; |
nothing calls this directly
no test coverage detected