Kodeco Forums

How To Make a Multiplayer iPhone Game Hosted on Your Own Server Part 1

A while back, I wrote a tutorial on How To Make A Simple Multiplayer Game with Game Center. That tutorial showed you how to use Game Center to create a peer-to-peer match. This means that packets of game data were sent directly between the connected devies, and there was no central game server. However, sometimes […]


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3040-how-to-make-a-multiplayer-iphone-game-hosted-on-your-own-server-part-1

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! :]