如何以编程方式关闭NSStream输入/输出

时间:2013-11-10 11:17:49

标签: ios sockets nsstream

我有一个将用户连接到服务器的应用程序。用户可以连接到主机以进行通信,插入IP地址并使用NSStream进行通信。按连接按钮可启动与主机的连接,用户可以接收和发送消息。

我想让用户能够断开与服务器的连接,而不是按下断开连接按钮。问题是我永远无法成功关闭流。

这是我目前的实施:

// Create connection "Connect Button"
- (void)initNetworkCommunication:(UIViewController *)sender {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"123.456.789.123", 80, &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];
    controller = sender;
}

// Stop connection "Disconnect Button"
- (void)stopNetworkConnection {
    [inputStream close];
    [outputStream close];
    [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream release];
    [outputStream release];
    inputStream = nil;
    outputStream = nil;
    NSLog(@"Disconnect from stream");
}

操作流程如下:

  1. 用户插入有效的IP地址;
  2. 用户按“连接按钮”;
  3. 一切正常,建立连接,用户可以发送/接收消息;
  4. 用户按“断开连接按钮”,用户不接收消息;
  5. 用户按“连接按钮”但无法再连接
  6. 我试过这个解决方案,但它不起作用:

    NSStream closing and opening error

    提前感谢您的帮助

0 个答案:

没有答案