Cocoa Socket Programming NSInputStream read returns 0

拟墨画扇 提交于 2020-01-03 04:45:13

问题


In my App, have setup the stream like this,

(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];

}

and event handled like below,

- (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];


                }

              }
    }
}

The problem is, read or getBuffer always returns 0, Am i missing something?

Thanks in Advance ,


回答1:


Not sure what the problem is with getBuffer:lenght: in your case, but this is how read:maxLength: should be used:

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.
}


来源:https://stackoverflow.com/questions/7014784/cocoa-socket-programming-nsinputstream-read-returns-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!