Code example for Socket

Methods: getLocalAddress, isClosed, isConnected

0
        mSocket.setSoTimeout(timeoutMilliseconds);
    } 
 
    public boolean isOpen() { 
        return (mIn != null && mOut != null && 
                mSocket != null && mSocket.isConnected() && !mSocket.isClosed());
    } 
 
    /** 
     * Close the connection.  MUST NOT return any exceptions - must be "best effort" and safe. 
     */ 
    public void close() { 
        try { 
            mIn.close();
        } catch (Exception e) {
            // May fail if the connection is already closed. 
        } 
        try { 
            mOut.close();
        } catch (Exception e) {
            // May fail if the connection is already closed. 
        } 
        try { 
            mSocket.close();
        } catch (Exception e) {
            // May fail if the connection is already closed. 
        } 
        mIn = null;
        mOut = null;
        mSocket = null;
    } 
 
    public InputStream getInputStream() {
        return mIn;
    } 
 
    public OutputStream getOutputStream() {
        return mOut;
    } 
     
    /** 
     * Writes a single line to the server using \r\n termination. 
     */ 
    public void writeLine(String s, String sensitiveReplacement) throws IOException {
        if (Config.LOGD && Email.DEBUG) {
            if (sensitiveReplacement != null && !Email.DEBUG_SENSITIVE) {
                Log.d(Email.LOG_TAG, ">>> " + sensitiveReplacement);
            } else { 
                Log.d(Email.LOG_TAG, ">>> " + s);
            } 
        } 
         
        OutputStream out = getOutputStream();
        out.write(s.getBytes());
        out.write('\r');
        out.write('\n');
        out.flush();
    } 
     
    /** 
     * Reads a single line from the server, using either \r\n or \n as the delimiter.  The 
     * delimiter char(s) are not included in the result. 
     */ 
    public String readLine() throws IOException {
        StringBuffer sb = new StringBuffer();
        InputStream in = getInputStream();
        int d;
        while ((d = in.read()) != -1) {
            if (((char)d) == '\r') {
                continue; 
            } else if (((char)d) == '\n') {
                break; 
            } else { 
                sb.append((char)d);
            } 
        } 
        if (d == -1 && Config.LOGD && Email.DEBUG) {
            Log.d(Email.LOG_TAG, "End of stream reached while trying to read line.");
        } 
        String ret = sb.toString();
        if (Config.LOGD) {
            if (Email.DEBUG) { 
                Log.d(Email.LOG_TAG, "<<< " + ret);
            } 
        } 
        return ret;
    } 
 
    public InetAddress getLocalAddress() {
        if (isOpen()) { 
            return mSocket.getLocalAddress();
        } else { 
            return null; 
        } 
    } 
}