I find these code on the website,and rewrite it into my current code ,I can successfully connect to the server side.But I still had some problems:
outputStream:
According to the code on the website, I can normally send string
- (IBAction)sendCmd:(id)sender
{
NSString *response = @"Hello World!";
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
But I want to send bytes,(e.g 0x80,0x10,0x20...etc.) Android syntax is:
byte[] buf=new byte[10];
buf[0]=(byte) 0x80;
buf[1]=(byte) 0x10;
buf[2]=(byte) 0x20;
But replaced ios,I don't know how to do? Give me some advice or website,grateful.
When you say "I have bytes", that presumably means either:
You have an NSData
or similar type holding the bytes. You can see how to get the bytes and length for that from your existing example—just skip the part where you encode the NSString
to an NSData
, because you already have an NSData
.
You have a raw C buffer (via a void *
or char *
or unsigned char *
or similar) and a length. That's exactly what -[NSOutputStream write: maxLength:]
wants from you; where your example passes [data bytes]
and [data length]
, just pass your pointer (possibly with a cast) and length values.
For example:
const char msg[] = "\x80\x10\x20";
const NSUInteger msglen = sizeof(msg) / sizeof(*msg);
[outputStream write:(const uint8_t *)msg maxLength:msglen];
If you really want an exact ObjC equivalent of your Android code for some bizarre reason, it would look something like this:
NSMutableData *data = [NSMutableData dataWithLength:10];
uint8_t *buf = (uint8_t *)[data mutableBytes];
buf[0]=(uint8_t)0x80;
buf[1]=(uint8_t)0x10;
buf[2]=(uint8_t)0x20;
[outputStream write:buf maxLength:3]; // or is that 10?
I'm not sure why you're creating a 10-byte buffer and only filling in 3 bytes, but +dataWithLength
does the same thing as Android Java and leaves the other 7 slots filled with 0's, if that's what you want.
(You can also just use calloc
and skip all the ObjC stuff if you want, but then you have to deal with checking for NULL
, calling free
at the end even if there was an error somewhere, etc., because C isn't Java…)