如何阻止CFSocket发送回调?

发布于 2024-12-08 11:16:40 字数 902 浏览 0 评论 0原文

我有一个服务器应用程序,它为每个连接的客户端创建一个对象。在此对象的 init 方法中,我使用此代码创建一个 CFSocket 来与客户端通信:

CFSocketContext context = {
    .info = self
};

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

当主程序完成与客户端的通信后,它会释放 ClientConnection< /code> 对象及其 dealloc 方法被调用:

CFSocketDisableCallBacks( socket, kCFSocketDataCallBack );

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

CFSocketInvalidate( socket );
CFRelease( socket );

完成之后,我仍然收到数据回调,这些回调被路由到现在已释放的对象,从而导致崩溃。

我尝试了所有我能想到的方法,但仍然无法完成这项工作。关于为什么 CFSocket 在失效后发送回调的任何想法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羞稚 2024-12-15 11:16:40

某些 CFSocket 回调在您禁用后可能会自动重新启用,尤其是 kCFSocketDataCallBack。回调函数似乎在您进行禁用调用和套接字失效之间被使用。

为了防止这种行为,您需要使用 CFSocketSetSocketFlags 禁用它们:

CFOptionFlags sockopt = CFSocketGetSocketFlags (mysock);
sockopt &= kCFSocketDataCallBack;
CFSocketSetSocketFlags(s, sockopt);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文