views:

113

answers:

1

Hi Everyone,

how can I avoid, to send data via CFSocketSendData to an invalid socket? I've try to determine the socket state with CFSockerIsValid, but this method returns still true when the other side is close.

So how can I determine if the socket is valid? In order so avoid Errors.

Thank Chris

A: 

If the other side closes the socket, your callback (which you specified in CFSocketCreate) will get invoked with a callback type of kCFSocketDataCallBack, yet the data will be empty. Test for it like this:

void SocketCallback (CFSocketRef s, CFSocketCallBackType callbackType,
                 CFDataRef address, const void *data, void *info)
{
    if (callbackType == kCFSocketDataCallBack) {
        NSData *nsData = (NSData *)data;
        if (nsData.length == 0) {
            NSLog(@"got kCFSocketDataCallBack, but with 0 bytes -- connection terminated");
            // do whatever you want to do here when connection is dropped
        }
    } else {
        NSLog(@"SocketCallback type %d", callbackType);
    }

}

You can set a flag there and use that to know that your connection is dropped, and then when you go to write to a dropped connection, attempt to reconnect or notify the user or whatever you want to do.

Joe Strout