目标c - 通过套接字发送固定数量的数据?

时间:2010-08-21 20:49:42

标签: objective-c sockets

每当我向服务器写入一些数据时,我首先发送一条包含号码的消息,该号码假定告诉服务器我要发送多少数据。

例如在发送1024个字节之前,我需要先将“1024”发送到服务器,然后服务器才能开始读取1024个字节。 如何确保发送到服务器的第一条消息(字节数)始终具有相同的大小?所以例如总是8个字节

    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
    ...
    ...
    ...

2 个答案:

答案 0 :(得分:0)

您是否想说服务器应该如何知道包含要接受的字节数的数据包的大小?

如果是这样,你可以继续接受逐字节,直到遇到一个分号或一些终止字符。从那里,组装数据包,然后你将有大小的数据来接收。

答案 1 :(得分:0)

解决方案:我将整数转换为nsdata,并将其发送到服务器,这样从整数创建的数据总是4个字节。 所以这就是流程

- 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];
}