0

我已经在我的项目中实现了套接字连接,并且工作正常。但我的问题是我想在套接字打开完成时发送一个字符串请求。

代表工作正常。

- (void)initNetworkCommunication
{
    lastString=@"";
    isSocketAuthorized=NO;
    NSLog(@"$$$$$$$$$$$$$$$$$$$$$$$$$============socket connection INITIALISED....");

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL,(CFStringRef)@"XXX.XX.XXX.XX",XXXX, &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge 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)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {

        case NSStreamEventOpenCompleted:{

            NSLog(@"Stream opened");
            [self performSelectorInBackground:@selector(sendAuthRequest) withObject:nil];
        }
            break;

        case NSStreamEventHasBytesAvailable:
        {
            if (aStream == inputStream) {

                uint8_t buffer[1024];
                int len;

                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {

                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                        if (nil != output) {
//                            NSLog(@"server said: %@", output);
                            [self messageReceived:output];
                        }
                    }
                }
            }
        }
            break;

        case NSStreamEventErrorOccurred:
            NSLog(@"Can not connect to the host!");
            break;

        case NSStreamEventEndEncountered:
        {
            [aStream close];
            [aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        }
            break;

        default:
            NSLog(@"Unknown event");
    }
}

但是 stream open 被调用了两次。为什么会这样?谁能帮我。谢谢。

4

1 回答 1

5

经过很长时间的脑筋急转弯,我才知道我实际上调用了两次开放流。第一次是输入流,第二次是输出流。最后我找到了触发我的方法一次的解决方案在没有调用的事件中,我使用了 NSStream 类的条件。

case NSStreamEventOpenCompleted:{

        if ([aStream isKindOfClass:[inputStream class]]) {
            NSLog(@"Input stream opened");
        }else{
            NSLog(@"output stream opened");
            [self performSelectorInBackground:@selector(sendAuthRequest) withObject:nil];
        }
    }
于 2013-06-11T03:59:19.003 回答