我在使用 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);
}