这是问题。当我的应用程序启动时,我通过端口5000连接到server1。我将数据发送到server1。 Server1发回数据。 Server1关闭连接。输入流发生NSStreamEventEndEncountered事件。然后,我在端口5001上连接到server2。尝试将数据发送到server2,但是数据最终到达了server1。输入流以某种方式在端口5001上连接,而输出流以5000方式连接。我在做什么错?

- (void) initNetworkCommunication: (uint32_t)port {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", port, &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];
}

- (void) onClientConnectionLost {
    if (atServer1 == YES) {
        atServer1 = NO;
        [self initNetworkCommunication: 5001];
    }
    if (atServer1 == NO) {
        atServer1 = YES;
        [self initNetworkCommunication: 5000];
    }
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    switch (streamEvent) {
        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            break;
        case NSStreamEventHasBytesAvailable:
            if (theStream == inputStream) {
                //handle packets...
            }
            break;
        case NSStreamEventErrorOccurred:
            NSLog(@"Can not connect to the host!");
            break;
        case NSStreamEventEndEncountered:
            if (theStream == inputStream) {
                [theStream close];
                [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
                [theStream release];
                theStream = nil;

                [outputStream close];
                [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
                [outputStream release];
                outputStream = nil;

                [self onClientConnectionLost];
            }
            break;
        default:
            NSLog(@"Unknown event");
    }
}

最佳答案

- (void) onClientConnectionLost {
if (atServer1 == YES) {
    atServer1 = NO;
    [self initNetworkCommunication: 5001];
}
else if (atServer1 == NO) {
    atServer1 = YES;
    [self initNetworkCommunication: 5000];
}


}

在您的旧代码上,当atServer1 = YES时,它将执行第一个if语句。

关于ios - NSOutputStream无法关闭?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15490159/

10-09 17:59