0

我希望读取来自 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);

但仍然无法获取字符串。这个问题与编码有关吗?以及我可以使用什么类型的编码来解决这个问题。

@nd 事情是我想从流中读取 iOS 上的整数、字符串、UTFCharacters。有什么方法可以读取缓冲区,即 readInteger()、readString() 和 readCharacter()。

4

1 回答 1

0

我不是 IOS 专家,但如果你想真正实现基于文本的协议DataOutputStream,请使用除writeUTF().

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

PrintWriter w = new PrintWriter(new OutputStreamWriter(response.getOutputStream()))

甚至只是

PrintWriter w = response.getWriter();

现在在那里写:

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

等等

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

于 2013-05-27T12:54:22.660 回答