2

我有一个将用户连接到服务的应用程序。用户可以连接到主机进行通信,插入 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. 用户按下“连接按钮”但不再能够连接

我尝试了这个解决方案,但没有奏效:

NSStream关闭和打开错误

在此先感谢您的帮助

4

0 回答 0