/** * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string * buffer to use ** @throws IOException if an error occurs or the server has stopped */ protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb) throws IOException { if (socket != null) { int dataLen = 0; StringBuffer data = (sb != null) ? sb : new StringBuffer(); InputStream input = socket.getInputStream(); while ((maxLen < 0) || (maxLen > dataLen)) { int ch = input.read(); // Print.logInfo("ReadLine char: " + ch); if (ch < 0) { // this means that the server has stopped throw new IOException("End of input"); } else if (ch == LineTerminatorChar) { // include line terminator in String data.append((char) ch); dataLen++; break; } else { // append character data.append((char) ch); dataLen++; } } return data.toString(); } else { return null; } }
/** * ** Reads the specified number of bytes from the specifed socket ** @param socket The socket * from which bytes are read ** @param length The number of bytes to read from the socket * ** @throws IOException if an error occured or the server has stopped */ protected static byte[] socketReadBytes(Socket socket, int length) throws IOException { if (socket == null) { return null; } else if (length <= 0) { return new byte[0]; } else { int dataLen = 0; byte data[] = new byte[length]; InputStream input = socket.getInputStream(); while (dataLen < length) { int ch = input.read(); if (ch < 0) { // this means that the server has stopped throw new IOException("End of input"); } else { data[dataLen] = (byte) ch; dataLen++; } } return data; } }
/** * ** Reads the bytes from the specifed socket until an eod-of-stream error occurs, or ** until * the maximum number of bytes has bee read. ** @param socket The socket from which bytes are read * ** @param baos The ByteArrayOutputStream to which the bytes are written ** @param maxLength The * number of bytes to read from the socket ** @return The number of bytes read if no exception has * occurred ** @throws IOException if an error occured or the server has stopped */ protected static int socketReadBytes(Socket socket, ByteArrayOutputStream baos, int maxLength) throws IOException { if (socket == null) { return 0; } else if (maxLength == 0) { return 0; } else { int dataLen = 0; InputStream input = socket.getInputStream(); while ((maxLength < 0) || (dataLen < maxLength)) { int ch = input.read(); if (ch < 0) { // we've reached the end of input return dataLen; } else { if (baos != null) { baos.write(ch); } dataLen++; } } return dataLen; } }