A few questions about the design of networking code

Discussion in 'iOS Programming' started by idelovski, Nov 16, 2010.

  1. idelovski macrumors regular

    Sep 11, 2008
    I am building a game that is played over the network. Bonjour is used to search for other devices and then they communicate utilizing NSStreams - NSInputStream and NSOutputStream.

    It all works well, except when there's a weak signal. When WiFi is lost for a moment everything just goes south.

    I have decided to try to reconnect when possible and I started changing my code, but I need some help from more experienced developers. One device is listening, the other picks it. For the server I store the address where it was listening, and for the other device I store the address it connects to. If the signal is lost, when NSStream reports errors or disconnection, one device starts listening at the same address it used before and the other device tries to reconnect to the same address it found the first time.

    This is how it goes.

    First I create socket with CFSocketCreate(), then I call setsockopt() to set SO_REUSEADDR. First time here, I set sockaddr_in struct to INADDR_ANY and put it into NSData, then pass that to CFSocketSetAddress(). If all is well, I store the address
    with CFSocketCopyAddress() so I can pass that later to CFSocketSetAddress() when I try to reconnect.

    The other party in -netServiceDidResolveAddress:, one of NSNetServiceDelegate methods stores the servers address so when connection is broken I can pass the same address to CFSocketConnectToAddress().

    Is this logic OK? Possible problems and gotchas? At my place WiFi is stable and works ok, I had trouble with the networks when I was showing my application to others at public places so I have no idea how to debug this thing. Should I deliberately disconnect at one side after a while and test what happens?

    If anyone’s interested I can post the code I have so far.
  2. vocaro macrumors regular

    Mar 5, 2004
    A couple of thoughts...

    1) NSStream uses TCP, a lossless protocol that is naturally sensitive to connection failures. Perhaps a protocol based on lossless UDP would be more resilient to transient connection failures.

    2) Switching to Game Kit's peer-to-peer APIs might make everything simpler.
  3. idelovski thread starter macrumors regular

    Sep 11, 2008
    Sometimes I send images over the network. Using UDP would probably makes things even more complicated.

    Isn't GameKit Bluetooth only? Maybe I should check it again.
  4. Luke Redpath macrumors 6502a

    Nov 9, 2007
    Colchester, UK
    GameKit operates over a local WiFI network too.

Share This Page