In case NSStreamEventOpenCompleted, there is no break. Is it deliberate. If yes, then what is the reason?
case NSStreamEventOpenCompleted: {
NSLog(@"Opened input stream");
_inputOpened = YES;
if (_inputOpened && _outputOpened && _state == NetworkStateConnectingToServer) {
[self setState:NetworkStateConnected];
// TODO: Send message to server
}
}
case NSStreamEventHasBytesAvailable: {
if ([_inputStream hasBytesAvailable]) {
NSLog(@"Input stream has bytes...");
// TODO: Read bytes
}
} break;
“One big gotcha here is that this method isn’t guaranteed to be called in the main thread. Because we’re going to be accessing some shared state in this method (instance variables on this class)” — Can you please help me to understand why it may not be called in main thread. My question may sound very stupid, but I am a newbie with socket programming, so please help me. Thanks in advance
Great tutorial! I’ve made some great use out of this. Just to note, I spotted a small mistake in the writeChunk() method.
int amtWritten = [self.outputStream write:_outputBuffer.bytes maxLength:amtToWrite];
if (amtWritten < 0) {
[self reconnect];
}
int amtRemaining = _outputBuffer.length - amtWritten;
etc....
In the very rare circumstances where the write fails, then amtWritten will be -1. Your code calls the reconnect method - which is fine - but it doesn’t exit the current method. Therefore, the -1 value will be used further down in the code causing a crash (due to index out of bounds). Sticking a return after calling the reconnect method should do the trick.
if (amtWritten < 0) {
[self reconnect];
return;
}
This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]