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

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

        CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
        inStream.open()
        outStream.open()
        
        self.mutex.lock()
        self.readyToWrite = true
        self.mutex.unlock()
        
        let bytes = UnsafePointer<UInt8>(data.bytes)
        var timeout = 5000000 //wait 5 seconds before giving up
        writeQueue.addOperationWithBlock { [unowned self] in
