Cocoa Socket编程NSInputStream读取返回0

时间:2011-08-10 17:00:46

标签: cocoa sockets objective-c++ nsstream

在我的应用中,设置了这样的流,

(void)connectStream:(NSString *)pHostName PortNo:(int)inPortNo HasInput:(bool)bInput HasOutput:(bool)bOutput{




    NSHost *host = [NSHost hostWithName:pHostName];

    //host = [NSHost hostWithAddress:pHostName];

    [NSStream getStreamsToHost:host port:inPortNo inputStream:&pInputStream
                  outputStream:&pOutputStream];

    [pInputStream retain];  

    [pOutputStream retain];

    [pInputStream setDelegate:self];

    [pOutputStream setDelegate:self];



    bool bUseSSL = YES;
    if (bUseSSL)
    { 

        [self setInputStreamSecurity];
        [self setOutputStreamSecurity];
    }


    [pOutputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                       forMode:NSDefaultRunLoopMode];

    [pInputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                            forMode:NSDefaultRunLoopMode];


    [pInputStream open];

    [pOutputStream open];

}

和事件处理如下,

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent{

       switch(streamEvent){
        case NSStreamEventHasBytesAvailable:{
        if([theStream hasBytesAvailable]){
                unsigned int len=0;

                NSUInteger intLen;
                [theStream getBuffer:&pInputBuffer length:&intLen];
                [theStream read:pInputBuffer maxLength:MAX_INPUT_BUFF_LEN];

                if(intLen){         
                  NSMutableData *data=[[NSMutableData alloc] init];
                  [data appendBytes:pInputBuffer length:len];

                  [WebSocketEventData postGotBytesEvent:data Len:len];
                 }else{
                   NSError *theError = [theStream streamError];
                   NSString *pString = [theError localizedDescription];
                   int errorCode = [theError code];


                }

              }
    }
}

问题是,read或getBuffer总是返回0,我错过了什么?

先谢谢,

1 个答案:

答案 0 :(得分:0)

在您的情况下不确定getBuffer:lenght:的问题是什么,但这应该是read:maxLength:应该使用的方式:

NSInteger bytesRead;

bytesRead = [theStream read:pInputBuffer maxLength:MAX_INPUT_BUFF_LEN];
if (bytesRead > 0) {
    // Handle input.
} else if (bytesRead == 0) {
    // Handle EOF.
} else {
    // Handle error.
}