当应用程序转到后台时关闭NSStreams

时间:2012-07-23 20:01:03

标签: ios tcp nsstream nsinputstream nsoutputstream

我是客观C和ios开发的新手。我通常使用Java编写Android应用程序,并始终使用onPause调用来关闭我的套接字。但是当我在applicationWillResignActive下调用我的close套接字方法时,我放松了与流监听器的通信,无法关闭输入和输出流。事实上,即使应用程序连接到服务器,两个流的流状态都显示NSStreamStatusNotOpen或0。有什么想法吗?

谢谢

修改

SocketHandler.m中的连接方法类:

  -(void)connect:(int *)port ipAddress:(NSString *)ipAddress
{
        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)ipAddress, port, &readStream, &writeStream);
        inputStream = (NSInputStream *)readStream;
        outputStream = (NSOutputStream *)writeStream;
        [inputStream setDelegate:self];
        [outputStream setDelegate:self];
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [inputStream open];
        [outputStream open];
        NSLog(@"input stream id %i", inputStream);  
}

-(void)disconnect{

    NSLog(@"disconnect method called");

    socketStatus = [outputStream streamStatus];
    int status = socketStatus;
    NSLog(@"Stream Status is %i", status);

    if (status == 2) {
        [inputStream close];
        [outputStream close];
        NSLog(@"Socket Closed");
    }



}

1 个答案:

答案 0 :(得分:0)

好的,这是我自己问题的答案。

我创建了3个类:

TCPSocketAppDelegate TCPSocketViewController 套接字处理程序

在Socket处理程序类中,我有一个叫做Connect的方法,另一个叫做Disconnect。他们在这里:

连接方法:

-(void)connect:(int *)port ipAddress:(NSString *)ipAddress
{
        NSLog(@"input stream id %i", inputStream);
        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)ipAddress, port, &readStream, &writeStream);
        inputStream = (NSInputStream *)readStream;
        outputStream = (NSOutputStream *)writeStream;
        [inputStream setDelegate:self];
        [outputStream setDelegate:self];
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [inputStream open];
        [outputStream open];
        NSLog(@"input stream id %i", inputStream);  
}

断开方法:

-(void)disconnect{

    NSLog(@"disconnect method called");
    NSLog(@"input stream id %i", inputStream);

    socketStatus = [outputStream streamStatus];
    int status = socketStatus;
    NSLog(@"Stream Status is %i", status);

    if (status == 2) {
        [inputStream close];
        [outputStream close];
        NSLog(@"Socket Closed");
    }



}
然后,我在TCPSocketAppDelegate类和TCPSocketView Controller类中为Socket Handler类创建了引用对象。但是,当我这样做时,它为每个创建了一个SocketHandler类的新实例,因此它们没有寻址同一个套接字,因此可以连接套接字但另一个无法访问它。为了解决这个问题,我简单地使用+(void)全局访问connect和disconnect方法。现在我不必在其他类中创建一个引用对象来调用方法。我希望这些信息可以帮助有人在路上。