我有一个将用户连接到服务的应用程序。用户可以连接到主机进行通信,插入 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");
}
操作流程如下:
- 用户输入一个有效的 IP 地址;
- 用户按下“连接按钮”;
- 一切正常,连接建立,用户可以发送/接收消息;
- 用户按下“断开按钮”,用户收不到消息;
- 用户按下“连接按钮”但不再能够连接
我尝试了这个解决方案,但没有奏效:
在此先感谢您的帮助