public SocketBot(String newUrl) { this.url = newUrl; sb = new StringBuffer(); }
/** * send and recieve some data */ publicvoid send() { SocketConnection conn; // open connection goes here try { conn = (SocketConnection) Connector.open(url); } catch (IOException e) { sb.append(e.toString()); return; } try { conn.setSocketOption(SocketConnection.DELAY, 0); InputStream recvStream = conn.openInputStream(); OutputStream sendStream = conn.openOutputStream(); // write something sendStream.write(HELLO.getBytes()); sendStream.write(CRLF.getBytes()); // append send data to log sb.append(SEND).append(HELLO).append(CRLF); // begin to read StringBuffer sbuf = new StringBuffer(); int c = 0; while ((c = recvStream.read()) != -1) { sbuf.append((char) c); } // put to log sb.append(RECV).append(sbuf.toString()).append(CRLF); // close input stream and output stream when done recvStream.close(); sendStream.close(); // append exception to log if any } catch (IllegalArgumentException e) { sb.append(e.toString()); } catch (IOException e) { sb.append(e.toString()); } finally { // do not forget to close the connection for re-use try { conn.close(); } catch (IOException ignored) { // should be ignored }
}
}
/** * retreive the result log * * @return */ public String retrieveLog() { return sb.toString(); }