Java tutorial
//package com.java2s; import java.net.Socket; 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 readNetSocket(Socket socket, int timeoutMS) throws Exception { byte[] buffer = new byte[MAX_BUF_LEN]; String ret = null; if (readNetSocketBytes(socket, timeoutMS, buffer, MAX_BUF_LEN) > 0) { ret = new String(buffer); } return ret; } public static int readNetSocketBytes(Socket socket, int timeoutMS, byte[] buffer, int maxLen) throws Exception { int ret = 0, timeout = -2, bytesAvailable = 0, curRead = 0, waitCount = 0; boolean haveData = false; InputStream is = socket.getInputStream(); 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(10); if (timeoutMS != 0) { timeout += 10; } else if ((haveData == true) && (waitCount++ > HAVE_DATA_WAIT_RETRIES)) { break; } } } return ret; } }