我目前正在创建一个基于Rey Wenderlich's chat app tutorial的聊天应用程序,除非我无法重新连接而无需再次从Xcode运行该应用程序,所以该功能非常好。
它是这样的:run server
- > run app
(此时,一切都很棒)然后我stop server
- > run server
再一次,我的溪流拒绝重新连接并继续给我一个erorr:Error Domain=NSPOSIXErrorDomain Code=61 "Connection refused"
。
为什么会这样?
初始化流的方法:
- (void)initStreams {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)SERVER_IP, port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
inputStream.delegate = self;
outputStream.delegate = self;
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
我的代表
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
NSString *streamName = @"Output Stream";
if (aStream == inputStream) {
streamName = @"Input Stream";
}
switch (eventCode) {
case NSStreamEventOpenCompleted:
NSLog(@"%@ opened! (%lu)",streamName, eventCode);
[_delegate socketDidOpenSuccessfully];
break;
case NSStreamEventHasBytesAvailable:
[self readDataFromStream:aStream];
break;
case NSStreamEventErrorOccurred:
NSLog(@"Error: %@",[aStream streamError]);
[self resetStreams];
break;
case NSStreamEventEndEncountered:
NSLog(@"%@ read ended! (%lu)",streamName, eventCode);
[self resetStreams];
break;
default:
NSLog(@"Unknown %@: %d",streamName, (int)eventCode);
break;
}
}
重置流方法:
- (void)resetStreams {
NSLog(@"Reseting!");
toSend = [NSMutableArray new];
_loginStatus = LTLoginStatusLoggedOut;
[inputStream close];
[outputStream close];
[self performSelector:@selector(initStreams) withObject:self afterDelay:2];
}
答案 0 :(得分:1)
因此,经过数小时的挫折之后,我决定将其包装在另一个对象中,并在它断开连接时重新实例化。似乎工作,而重新启动流不会。