문제

I've opened the following input and output streams through the External Accessory Framework:

session = [[EASession alloc] initWithAccessory:acc forProtocol:protocol];

        if (session){
            [[session inputStream] setDelegate:self];
            [[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [[session inputStream] open];

            [[session outputStream] setDelegate:self];
            [[session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [[session outputStream] open];
        }

Now I have a very dumb question, as most of my newbie questions are. How can I sent raw 1 byte pieces of data to the stream? Say, I want to send 0x06. How do I do that?

And then...how do I read data from the stream? I will be sent back data to be processed byte by byte...the bytes will be numbers in the byte range (0x00 – 0xFF).

Thank you for your patience and help!

도움이 되었습니까?

해결책

Writing data byte-by-byte is not the most efficient way, but if you insist:

uint8_t aByte = 0x06;
if ([[session outputStream] write:&aByte maxLength:1] < 0)
    /* handle error */;

Likewise, to read byte-by-byte:

uint8_t aByte;
NSInteger result = [[session inputStream] read:&aByte maxLength:1];
if (result > 0)
    /* handle received byte */;
else if (result == 0)
    /* handle end-of-stream */;
else
    /* handle error */;

If you want to read or write larger chunks of data, pass a pointer to a larger-than-one-byte buffer and specify the length. Be sure to handle short reads and writes, where the return code is positive but less than you specified. You need to wait for the stream to be ready for more and continue where it left off. For reading, you might also use -getBuffer:length:, where the framework allocates a buffer of a length of its choosing.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top