【发布时间】:2011-02-23 16:40:31
【问题描述】:
我在使用 DataInputStreams 时遇到了一些问题,
所以我有数据来自本地服务器,我知道我读入的字节将遵循这种格式
0x01 指定它是一个字符串
然后是随机字节数
后跟0x00 0x00,
不过,我无法从服务器读取数据,
这是我的阅读方法
public static String convertFromServer(DataInputStream dis) throws IOException{
//Buffer to hold bytes being read in
ByteArrayOutputStream buf = new ByteArrayOutputStream();
if(dis.read() != -1){
//Check to see if first byte == 0x01
if(dis.read() == 0x01){
//Check if byte dosnt equal 0x00, i need it to check if it is actually 0x00 0x00
while(dis.read() != 0x00){
buf.write(dis.read());
}
}
if(dis.read() == 0x03){
while(dis.read() != 0x00){
buf.write(dis.read());
}
}
}
String messageRecevied = new String(buf.toByteArray());
return messageRecevied;
}
如果我有点模棱两可,请告诉我。
我正在取回数据,它只是不完全正确,基本上我所做的是通过一个字节数组发送,第一个元素是 0x01 来指定字符串,然后是字节字符串,最后是最后两个元素0x00和0x00,然后这个数据从服务器发回给我,服务器肯定收到了数据,只是我读回来的时候不正确,会丢失字母
此代码将数据编码为 0x01 格式,然后是字节消息,然后是 0x00,0x00
public static void writeStringToBuffer(ByteArrayOutputStream buf,String message){
buf.write(0x01);
byte[] b = message.getBytes();
for(int i =1; i<message.getBytes().length+1;i++ ){
buf.write(b[i-1]);
}
buf.write(0x00);
buf.write(0x00);
}
【问题讨论】:
-
好吧,你只检查了一个 0(但你已经知道了),它背后也可能有一个经济问题。你能告诉我们将数据写入流的代码吗?
-
我用我如何编码消息更新了问题,然后我使用 dataOutputStream.write(ByteArrayOutputStream.toByteArray()) 发送它,数据被接收并正确显示在服务器端与 0x01 , 0x00,0x00 去掉再转成字符串
标签: java byte bytebuffer