     //disconnect the stream object
     private func disconnectStream(error: NSError?) {
         writeQueue.waitUntilAllOperationsAreFinished()
+        cleanupStream()
+        doDisconnect(error)
+    }
+    
+    private func cleanupStream() {
+        outputStream?.delegate = nil
+        inputStream?.delegate = nil
         if let stream = inputStream {
             CFReadStreamSetDispatchQueue(stream, nil)
             stream.close()

            stream.close()
        }
        outputStream = nil
        certValidated = false
        doDisconnect(error)
    }
    
    ///handles the incoming bytes and sending them to the proper processing method

                usleep(100) //wait until the socket is ready
                timeout -= 100
                if timeout < 0 {
                    self.cleanupStream()
                    self.doDisconnect(self.errorWithDetail("write wait timed out", code: 2))
                    return
                } else if outStream.streamError != nil {
                    return //disconnectStream will be called.
                }
            }
            outStream.write(bytes, maxLength: data.length)
        }
    }
