首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSOutputStream不能关闭吗?

NSOutputStream不能关闭吗?
EN

Stack Overflow用户
提问于 2013-03-19 09:48:41
回答 1查看 464关注 0票数 0

这是问题所在。当我的应用程序启动时,我在5000端口连接到server1。我将数据发送到server1。Server1将数据发回。Server1关闭连接。inputStream发生NSStreamEventEndEncountered事件。然后,我在端口5001连接到server2。我尝试将数据发送到server2,但数据最终发送到了server1。不知何故,inputStream连接在5001端口,而我的outputStream连接在5000端口。我做错了什么?

代码语言:javascript
复制
- (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");
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-19 10:18:11

代码语言:javascript
复制
- (void) onClientConnectionLost {
if (atServer1 == YES) {
    atServer1 = NO;
    [self initNetworkCommunication: 5001];
}
else if (atServer1 == NO) {
    atServer1 = YES;
    [self initNetworkCommunication: 5000];
}

}

在你的旧代码上...当atServer1 = YES时,它将执行第一个if语句...这会将atServer1设置为NO...所以第二个if语句为真..因此,它还将执行..

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15490159

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档