0

TCPポート3000からデータを読み取るためのコードを書きました

- (BOOL)connect
{
int cIter = 0;
while(cIter++<5)
{
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    @try{
        CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)M_CONNECT_HOST, M_CONNECT_PORT, &readStream, &writeStream);
    }
    @catch (NSException *ex) {

    }
    if(readStream!=nil && writeStream!=nil)
    {
        m_sin = (__bridge NSInputStream *)readStream;
        m_sout = (__bridge NSOutputStream *)writeStream;
        [m_sin setDelegate:self];
        [m_sout setDelegate:self];

        [m_sin scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [m_sout scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [m_sin open];
        [m_sout open];

        return  true;
    }
}
return false;
}

tcp出力ストリームに書き込むと機能しますが、tcp入力ストリームから読み取ろうとすると読み取れません。つまり、[m_sin read:t maxlength:10]; 常に-1を返します(m_sinは私の入力ストリームです)

そして、ターミナルでデータをtcpポートに渡します

私を助けてください

4

1 に答える 1

0

handleEvent を実装し、eventCodeを確認します

 -(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{

    switch (eventCode) {
        case NSStreamEventOpenCompleted:
            NSLog(@"stream opened");
            break;

        case NSStreamEventHasBytesAvailable:            

            if (aStream == inputStream) {
                // read it in
                unsigned int len = 0;
                len = [inputStream read:buf maxLength:1019];
                buf[len] = '\0';

                if(!len) {

                    if ([aStream streamStatus] != NSStreamStatusAtEnd){

                        NSLog(@"Failed reading data from peer");

                    }

                } else {

                     //I am reading UIImage here                 
                     NSData *data = [NSData dataWithBytes:(const void *)buf length:1019];                    
                     UIImage *image = [UIImage imageWithData:data];
                     self.transferedimage.image = image;


                }
            }

            break;

        case NSStreamEventErrorOccurred:
            NSLog(@"stream ErrorOccurred");
            break;

        case NSStreamEventEndEncountered:
            NSLog(@"stream EndEncountered");
            break;

        default:
            NSLog(@"stream UnKnown");
            break;
    }
}
于 2012-11-21T11:07:41.057 に答える