Skip to content

Commit

Permalink
Merge pull request #302 from Elethier/operation-cancellation
Browse files Browse the repository at this point in the history
Fixed issues with not cancelling block operations properly
  • Loading branch information
daltoniam authored Jan 11, 2017
2 parents b22fae4 + c63e173 commit 33a4551
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions Source/WebSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,12 @@ open class WebSocket : NSObject, StreamDelegate {

let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
var out = timeout * 1_000_000 // wait 5 seconds before giving up
writeQueue.addOperation { [weak self] in
while !outStream.hasSpaceAvailable {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation else { return }
while !outStream.hasSpaceAvailable && !sOperation.isCancelled {
usleep(100) // wait until the socket is ready
guard !sOperation.isCancelled else { return }
out -= 100
if out < 0 {
self?.cleanupStream()
Expand All @@ -387,8 +390,10 @@ open class WebSocket : NSObject, StreamDelegate {
return // disconnectStream will be called.
}
}
guard !sOperation.isCancelled else { return }
outStream.write(bytes, maxLength: data.count)
}
writeQueue.addOperation(operation)
}

/**
Expand Down Expand Up @@ -847,9 +852,11 @@ open class WebSocket : NSObject, StreamDelegate {
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperation { [weak self] in
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let s = self else { return }
guard let sOperation = operation else { return }
var offset = 2
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
Expand All @@ -876,7 +883,7 @@ open class WebSocket : NSObject, StreamDelegate {
offset += 1
}
var total = 0
while true {
while !sOperation.isCancelled {
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = outStream.write(writeBuffer, maxLength: offset-total)
Expand All @@ -903,8 +910,8 @@ open class WebSocket : NSObject, StreamDelegate {
break
}
}

}
writeQueue.addOperation(operation)
}

/**
Expand Down

0 comments on commit 33a4551

Please sign in to comment.