2016-03-12 79 views
1

我目前正在創建一個基於Rey Wenderlich's chat app tutorial的聊天應用程序,除了我無法重新連接而無需運行應用程序Xcode再次。NSStream拒絕重新連接一旦斷開連接(獲取「錯誤61 - 連接被拒絕」)

它是這樣的: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]; 
} 

回答

1

那麼沮喪了幾個小時之後,我決定只把它包在另一對象並重新實例化,每當它斷開連接。似乎工作,而重新啓動流不會。