         guard !didDisconnect else { return }
         didDisconnect = true
         isConnecting = false
+        connectedMutex.lock()
         connected = false
+        connectedMutex.unlock()
         guard canDispatch else {return}
         callbackQueue.async { [weak self] in
             guard let s = self else { return }

        inStream.open()
        outStream.open()

        self.mutex.lock()
        self.readyToWrite = true
        self.mutex.unlock()
        
        let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
        var out = timeout * 1_000_000 // wait 5 seconds before giving up

                return code
            }
            isConnecting = false
            connectedMutex.lock()
            connected = true
            connectedMutex.unlock()
            didDisconnect = false
            if canDispatch {
                callbackQueue.async { [weak self] in
