无法从tcp端口读取数据

时间:2012-11-21 10:28:39

标签: objective-c ios objective-c-blocks

我已经编写了从tcp port 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读取:t maxlength:10]; 总是返回-1(其中m_sin是我的输入流)

我将数据通过终端

传递给tcp端口

请帮帮我

1 个答案:

答案 0 :(得分: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;
    }
}