Java 从服务器读取二进制数据

Java 从服务器读取二进制数据,java,objective-c,xcode,inputstream,binary-data,Java,Objective C,Xcode,Inputstream,Binary Data,我想从java服务器读取二进制数据,比如 DataOutputStream dos = new DataOutputStream(response.getOutputStream()); //dos.writeInt(5); dos.writeUTF("some text"); dos.flush(); 在iOS端 [stream open]; Byte buffer[100]; NSMutableData *data = [[NSMutableData alloc] init]; while

我想从java服务器读取二进制数据,比如

DataOutputStream dos = new DataOutputStream(response.getOutputStream());
//dos.writeInt(5);
dos.writeUTF("some text");
dos.flush();
在iOS端

[stream open];
Byte buffer[100];
NSMutableData *data = [[NSMutableData alloc] init];
while ([stre.stream hasBytesAvailable])
{
    int bytesRead = [stre.stream read:buffer maxLength:100];
    if(bytesRead == -1)
        continue;
   // bytesRead -= 2; //exclude the binary header
    [data appendBytes:buffer length:bytesRead];

}
[stre.stream close];

NSString * temp = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

NSLog(@"%@", temp);
但仍然无法获取字符串。这个问题与编码有关吗?对于这个问题,我可以使用什么类型的编码


@第二件事是我想从流中读取iOS上的整数、字符串和UTFCharacter。有没有办法读取缓冲区,即readInteger()、readString()和readCharacter()

我不是IOS方面的专家,但如果您真的想要实现基于文本的协议,请使用除
DataOutputStream
以外的工具,并且无论如何不要使用
writeUTF()

用于基于纯文本的协议使用

PrintWriter w = new PrintWriter(new OutputStreamWriter(response.getOutputStream()))
甚至只是

PrintWriter w = response.getWriter();
现在,这里的作者:

w.print(str);
w.println(str);
等等


如果要组合二进制数据和字符串数据,请使用
DataOutputStream.writeChars(str)

您使用的是NSASCIIStringEncoding来解码字符串,您不应该使用NSUTF8StringEncoding吗?Marcel,我也尝试过NSUTF8StringEncoding,但没有成功。谢谢你,谢谢你。我想用UTF格式发送二进制数据,在UTF格式中,每个字符需要1个字节,但如果我通过writeChars发送数据,每个字符需要2个字节,因此带宽增加了一倍。第二个问题是我必须以本地化格式发送数据,我想writeChars不支持本地化字符串