objective-cnsstream

How should you handle the possibility of an NSStream blockage?


Per Apple’s “Polling Versus Run-Loop Scheduling”:

[hasSpace/BytesAvailable] can mean that there is available bytes or space or that the only way to find out is to attempt a read or a write operation (which could lead to a momentary block).

The doc does not explicitly state that hasSpace/BytesAvailable events behave the same way, only, obscurely, that they have “identical semantics."

Am I to conclude that a write/read streamError or a bytes read/written return of less than the amount expected could be due to a “momentary block”?

If so, should I attempt the transmission again? Should I use some sort of timer mechanism to give the blockage a chance to clear? This would be a lot of work to implement, so I’d rather not if it’s unlikely to help.

(It’s tempting to initiate a limited polling loop in such a case, say a while loop that makes 10 attempts, but I don’t know if it’s safe to do that at the same time as the stream is scheduled in the run loop, and I have no way to test it.)


Solution

  • Here is a good wrapper for sockets: https://github.com/robbiehanson/CocoaAsyncSocket

    It will queue reads and writes if the connection is not available. You don't mention if you're using UDP or TCP, however I suspect you're using TCP, in which case it will handle any interruptions on its own -- provided the connection doesn't get torn down.