How to stop CFSocket from sending callbacks?

1.4k views Asked by At

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?

1

There are 1 answers

1
Paul Lynch On

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);