我有一點與DataInputStreams麻煩從服務器讀取數據需要,幫助在Java
所以我有數據來本地服務器,我知道,我讀字節格式如下
0x01至指定它是一個字符串
然後隨機字節量
後面有尾隨0×00 0×00,
我有這裏的麻煩,雖然從服務器讀取,
是我讀
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指定字符串,然後字符串以字節爲單位,最後是最後2個元素是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(但你alraedy知道),而且還可能是一個econding問題後面。你能向我們展示將數據寫入流的代碼嗎? – biziclop 2011-02-23 16:57:36
我更新瞭如何編碼消息的問題,然後我使用dataOutputStream.write(ByteArrayOutputStream.toByteArray())發送它,數據接收並正確顯示服務器端與0x01,0x00,0x00刪除,然後轉換到字符串 – molleman 2011-02-23 17:01:53