views:

29

answers:

2

every time i am writing some data to my server i first send a message containing a number which is suppose to tell the server how much data i am going to send.

For example before sending 1024 bytes, i need to first send the "1024" to the server then server can start reading for 1024 bytes. How can i make sure the first message (number of bytes) that i send to the server always has the same size? so for example always 8 bytes

    server - reading 8 bytes
    server - reading the number of bytes mentioned from last message
    server - reading 8 bytes
    server - reading the number of bytes mentioned from last message
    ...
    ...
    ...
A: 

Are you trying to say how should the server know how large the packet holding the number of bytes to accept is?

If so, you could just keep accepting byte after byte until, say, a semi-colon or some terminating character is encountered. From there, assemble the packets, and then you'll have the size of the data to recieve.

dmags
no i am trying to let the server know how much data i am sending before i send the actual data, because the data i am sending is the data from an image, so i need to start reading for the exact amount of bytes for the image to receive it correctly
aryaxt
A: 

Solution: I convert an integer to nsdata, and send it to the server, this way the data created from the integer is always 4 bytes. So this is the flow

- Server is reading (waiting for 4 bytes)
- Client sends 4 bytes containing an integer
- Client sends the actual data
- Server reads 4 bytes convert it to an integer
- Server reads for the amount of bytes it received in the last message
...
...

-(void)SendData: (NSData*)msgData
{
    int i = (int) msgData.length;
    NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];
    [self.soc writeData:data withTimeout:-1 tag:0];
    [self.soc writeData:msgData withTimeout:-1 tag:0];
}
aryaxt