我有一个将用户连接到服务器的应用程序。用户可以连接到主机以进行通信,插入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");
}
操作流程如下:
我试过这个解决方案,但它不起作用:
NSStream closing and opening error
提前感谢您的帮助