0

我是 Objective C 和 ios 开发的新手。我通常使用 Java 编写 Android 应用程序,并且总是使用 onPause 调用来关闭我的套接字。但是,当我在 applicationWillResignActive 下调用我的关闭套接字方法时,我与我的流侦听器失去了通信,并且无法关闭输入和输出流。事实上,即使应用程序连接到服务器,两个流的流状态都显示 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");
    }



}
4

1 回答 1

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) 使连接和断开连接方法全局可访问。现在我不必在其他类中创建引用对象来调用方法。我希望这些信息对以后的人有所帮助。

于 2012-07-26T15:41:27.553 回答