调试我的实现时,我发现了内存泄漏问题。我知道问题出在哪里,我试图解决它,但遗憾的是没有成功。我会尝试向您解释,也许你们中的某个人可以帮助您。
首先,这个问题涉及两个类,发布类(发布服务和套接字配置完成)和连接(完成套接字绑定和流配置)。主要问题在于通过本机套接字的连接。在“发布”类中,“服务器”接受带有回调的连接。回调具有本机套接字信息。然后,创建带有本机套接字信息的连接。接下来,套接字绑定和流配置完成。当这些操作成功时,连接实例将保存在一个可变数组中。因此,建立了连接。
static void AcceptCallback(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
Publish *rePoint = (Publish *)info;
if ( type != kCFSocketAcceptCallBack) {
return;
}
CFSocketNativeHandle nativeSocketHandle = *((CFSocketNativeHandle *)data);
NSLog(@"The AcceptCallback was called, a connection request arrived to the server");
[rePoint handleNewNativeSocket:nativeSocketHandle];
}
- (void)handleNewNativeSocket:(CFSocketNativeHandle)nativeSocketHandle{
Connection *connection = [[[Connection alloc] initWithNativeSocketHandle:nativeSocketHandle] autorelease]; // Create the connection
if (connection == nil) {
close(nativeSocketHandle);
return;
}
NSLog(@"The connection from the server was created now try to connect");
if ( ! [connection connect]) {
[connection close];
return;
}
[clients addObject:connection]; //save the connection trying to avoid the deallocation
}
下一步是从客户端接收信息,因此使用已建立连接的信息触发读取流回调。但是当回调处理程序尝试使用此连接时,会发生错误,它表示此类连接已被释放。这里的问题是我不知道连接在何处/何时被释放以及如何知道它。我正在使用调试器,但经过一些试验,我看不到更多信息。
void myReadStreamCallBack (CFReadStreamRef stream, CFStreamEventType eventType, void *info) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Connection *handlerEv = [[(Connection *)info retain] autorelease]; // The error -[Connection retain]: message sent to deallocated instance 0x1f5ef0 (Where 0x1f5ef0 is the reference to the established connection)
[handlerEv readStreamHandleEvent:stream andEvent:eventType];
[pool drain];
}
void myWriteStreamCallBack (CFWriteStreamRef stream, CFStreamEventType eventType, void *info){
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
Connection *handlerEv = [[(Connection *)info retain] autorelease]; //Sometimes the error also happens here, I tried without the pool, but it doesn't help neither.
[handlerEv writeStreamHandleEvent:eventType];
[p drain];
}
奇怪的是,当我运行调试器(带断点)时,一切顺利,连接没有解除分配,回调工作正常,服务器能够接收消息。我将不胜感激任何提示!