0

I have a server app which creates an object for every client that connects. In this object's init method I use this code to create a CFSocket to communicate with the client:

CFSocketContext context = {
    .info = self
};

socket = CFSocketCreateWithNative( kCFAllocatorDefault, nativeSocket, kCFSocketDataCallBack, SocketCallback, &context );
source = CFSocketCreateRunLoopSource( kCFAllocatorDefault, socket, 0 );
CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );

When the main program is done with the client it releases the ClientConnection object and it's dealloc method gets called:

CFSocketDisableCallBacks( socket, kCFSocketDataCallBack );

CFRunLoopRemoveSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
CFRelease( source );

CFSocketInvalidate( socket );
CFRelease( socket );

After that is done I still receive data callbacks which get routed to the now deallocated object which causes a crash.

I tried everything I can think off, but I still can't make this work. Any ideas about why the CFSocket is sending callbacks after it has been invalidated?

Sven
  • 22,475
  • 4
  • 52
  • 71
  • Solved this problem. Without realizing it I was calling the release (and thus the dealloc) from inside the callback handler. Turns out that CFSocket doesn't like that. – Sven Oct 05 '11 at 15:29

1 Answers1

1

Some CFSocket callbacks may be automatically reenabled after you have disabled them, notably kCFSocketDataCallBack. It seems likely that the callbacks are being used between the time you made the disable call, and when the socket was invalidated.

To prevent this behaviour, you need to disable them with CFSocketSetSocketFlags:

CFOptionFlags sockopt = CFSocketGetSocketFlags (mysock);
sockopt &= kCFSocketDataCallBack;
CFSocketSetSocketFlags(s, sockopt);
Paul Lynch
  • 19,769
  • 4
  • 37
  • 41
  • 1
    Good information, but this was not the problem. Turns out CFSocket doesn't like to be invalidated from inside a callback handler. – Sven Oct 05 '11 at 15:27