0

I'm new to iOS socket programming. I've implemented a tcp server with erlang with {packet, 4}, it is easy to communicate between erlang sockets. But how can I prepend packet's length in 4 bytes in AsyncSocket?

Some codes is appreciated.

I tested like following, but no effect on my server side:

int s = 10;
NSMutableData *headData = [NSMutableData dataWithBytes:&s length:4];

const char *body = [@"hello" UTF8String];
NSMutableData* bodyData = [NSMutableData dataWithBytes:body length:strlen(body)];

[sock writeData:headData withTimeout:-1 tag:100];
[sock writeData:bodyData withTimeout:-1 tag:101];
goofansu
  • 2,277
  • 3
  • 30
  • 48

1 Answers1

0

You are telling the server that you are sending 10 bytes, when you are actually not. You need to use the actual length of the data you are sending. And, also, since the server may have a different endianness than your machine, you need to decide on whether the length is little-endian or big-endian in your protocol:

const char *body = [@"hello" UTF8String];
NSMutableData* bodyData = [NSMutableData dataWithBytes:body length:strlen(body)];

uint32_t s = strlen(body);
uint32_t swapped = CFSwapInt32HostToBig(s)
NSMutableData *headData = [NSMutableData dataWithBytes:&swapped length:4];

[sock writeData:headData withTimeout:-1 tag:100];
[sock writeData:bodyData withTimeout:-1 tag:101];
Donovan Voss
  • 1,450
  • 13
  • 12