Java tutorial
//package com.java2s; import java.io.InputStream; public class Main { public static final int MAX_BUF_LEN = 32768; private static final int HAVE_DATA_WAIT_RETRIES = 3; public static String readSCSocket(InputStream is, int timeoutMS) throws Exception { byte[] buffer = new byte[MAX_BUF_LEN]; String ret = null; if (readSCSocketBytes(is, timeoutMS, buffer, MAX_BUF_LEN) > 0) { ret = new String(buffer); } return ret; } public static int readSCSocketBytes(InputStream is, int timeoutMS, byte[] buffer, int maxLen) throws Exception { int ret = 0, timeout = -2, bytesAvailable = 0, curRead = 0, waitCount = 0; boolean haveData = false; while (timeout < timeoutMS) { bytesAvailable = is.available(); if (bytesAvailable > 0) { haveData = true; waitCount = 0; curRead = ((bytesAvailable > (maxLen - ret)) ? (maxLen - ret) : bytesAvailable); curRead = is.read(buffer, ret, curRead); ret += curRead; if (ret >= maxLen) { return ret; } } else { if (timeoutMS == -1) { break; } Thread.sleep(100); if (timeoutMS != 0) { timeout += 100; } else if ((haveData == true) && (waitCount++ > HAVE_DATA_WAIT_RETRIES)) { break; } } } return ret; } }