0

我试图弄清楚如何以及是否可以通过 TCP 套接字发送和接收数组。我是目标 C 的新手,但我已经能够发送和接收字符串。我现在只想让它做数组。

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

NSLog(@"stream event %i", streamEvent);

switch (streamEvent) {

    case NSStreamEventOpenCompleted:
        NSLog(@"Stream opened");
        break;
    case NSStreamEventHasBytesAvailable:

        if (theStream == inputStream) {

            uint8_t buffer[1024];
            int len;

            while ([inputStream hasBytesAvailable]) {
                len = [inputStream read:buffer maxLength:sizeof(buffer)];
                if (len > 0) {
                    output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                    if (nil != output) {



                        chSent = [output substringWithRange: NSMakeRange (0, 6)];

                        dimensionString = [output substringWithRange: NSMakeRange (7, 3)];
                        colorString = [output substringWithRange: NSMakeRange (7, 3)];


                         if ([chSent isEqualToString:@"dimen:"])
                        {

                            dimensionInt = [dimensionString intValue];

                        }

                        if ([chSent isEqualToString:@"color:"]) {

                           // insert array named color in here some how

                        }                                


                    }
                }
            }
        }
        break;


    case NSStreamEventErrorOccurred:

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

    case NSStreamEventEndEncountered:

        [theStream close];
        [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
       // [theStream release];
        theStream = nil;

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

这就是我所拥有的。我放的地方//插入数组是我要放的地方

如果您能提供帮助,请提前致谢。

4

1 回答 1

1

您可以将数组数据(例如整数)作为除以某个分隔符的字符串“color:1;2;3;4;”发送 然后将字符串分开。如果您需要传递更复杂的数据结构,您可以编码、发送、解码。看看 NSKeyedArchiver 类。

于 2012-03-10T14:52:44.167 回答