public void doHandshake() throws Exception {

    // Begin handshake
    engine.beginHandshake();
    SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();

    // Process handshaking message
    while (hs != SSLEngineResult.HandshakeStatus.FINISHED &&
        hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {

        switch (hs) {

        case NEED_UNWRAP:
            // Receive handshaking data from peer
            pull(peerNetData);
            //if (pull(peerNetData) < 0) {
                // Handle closed channel
            //}

            // Process incoming handshaking data
            peerNetData.flip();
            SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
            peerNetData.compact();
            hs = res.getHandshakeStatus();

            // Check status
            switch (res.getStatus()) {
            case OK :
                // Handle OK status
                break;

            // Handle other status: BUFFER_UNDERFLOW, BUFFER_OVERFLOW, CLOSED
            //...
            }
            break;

        case NEED_WRAP :
            // Empty the local network packet buffer.
            myNetData.clear();

            // Generate handshaking data
            res = engine.wrap(myAppData, myNetData);
            hs = res.getHandshakeStatus();

            // Check status
            switch (res.getStatus()) {
            case OK :
                //myNetData.flip();

                push(myNetData);
                // Send the handshaking data to peer
                //while (myNetData.hasRemaining()) {
                //    if (push(myNetData) < 0) {
                //        // Handle closed channel
                //    }
                //}
                break;

            // Handle other status:  BUFFER_OVERFLOW, BUFFER_UNDERFLOW, CLOSED
            //...
            }
            break;

        case NEED_TASK :
            // Handle blocking tasks
            executeTasks();
            break;

        // Handle other status:  // FINISHED or NOT_HANDSHAKING
        //...
        }
      hs = engine.getHandshakeStatus();
    }

    // Processes after handshaking
    //...
}