2013-10-28 35 views
-1

我有一個類包含兩個具有一些變量的類對象。我想通過帶發送功能的USB發送類的實例(並在另一端接收)。 send函數接受字節數組(byte [])。將類對象轉換爲字節緩衝區

我的問題是我如何將類的實例轉換爲字節數組,以便我可以發送它?我如何在另一邊正確地重建它?

下面是我想要發送和接收的te類Comsstruct。歡迎任何提示!

 // ObjectInfo struct definition 
public class ObjectInfo { 
    int ObjectXCor; 
    int ObjectYCor; 
    int ObjectMass; 
}; 

// ObjectInfo struct definition 
public class SensorDataStruct{ 
    int PingData; 
    int IRData; 
    int ForceData; 
    int CompassData; 
}; 

// ObjectInfo struct definition 
public class CommStruct{ 
     public ObjectInfo VisionData; 
     public SensorDataStruct SensorData; 
}; 

public CommStruct SendPacket; 
public CommStruct RecievePacket; 

更新

我已經找到了解決方案,但與我有我不知道這是否會工作(如果它是一個很好的解決方案)的建議嗎?

有一個serialsation方法和發送方法:

// Method to convert object to a byte array 
public static byte[] serializeObject(CommStruct obj) throws IOException 
{ 
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); 
    ObjectOutputStream oos = new ObjectOutputStream(bytesOut); 
    oos.writeObject(obj); 
    oos.flush(); 
    byte[] bytes = bytesOut.toByteArray(); 
    bytesOut.close(); 
    oos.close(); 
    return bytes; 
} 

// Send struct function 
public void Send(){ 

    try 
{ 
     // First convert the CommStruct to a byte array 
     // Then send the byte array 
     server.send(serializeObject(SendPacket)); 

} 
    catch (IOException e) 
{ 
    Log.e("microbridge", "problem sending TCP message", e); 
} 

而且一收到處理函數:

public void onReceive(com.example.communicationmodulebase.Client client, byte[] data) 
{ 

    // Event handler for recieving data 


    // Try to receive CommStruct 
    try 
    { 
     ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); 
     ObjectInputStream ois = new ObjectInputStream(bytesIn); 
     RecievePacket = (CommStruct) ois.readObject(); 
     ois.close(); 
    } 
    catch (IOException e) 
    { 
     Log.e("microbridge", "problem recieving TCP message", e); 
    } 
    catch (ClassNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     Log.e("microbridge", "problem recieving TCP message", e); 
    } 

    // Send the recieved data packet back 
    SendPacket = RecievePacket; 

    // Send CommStruct 
    Send(); 
} 

我的問題是,如果這是一個很好的解決方案或沒有?

+0

http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array – Chill

+0

在您對我的回答的評論中,您說接收器將運行在Arduino上?你寫的接收器是用Java編寫的?我很抱歉,但如果不知道更確切地說明你想要完成的是什麼,就很難給出正確的答案。 –

回答

4

你可以有你的類實現Serializable interface,然後發送了一個字節流。但這是一個非常糟糕的主意,很可能無法工作。

爲什麼這不起作用,或者不能保證工作的原因是,不能保證java的不同實現將使用相同的序列化機制,因此字節陣列可能會在不同的Java implementations中有所不同。

相反,我建議您將對象轉換爲xml或json等中間格式,然後發送。這樣接收器甚至不需要用java編碼。

+0

感謝您的評論,其他人是Arduino微控制器。這兩個系統通過adb/usb連接。 Arduino代碼是C/C++。我找到了一些解決方案,並會在更新後發佈。你認爲這是一個很好的解決方案,並將工作或使用JSON? – Roy08

+0

C/C++代碼將無法讀取/寫入序列化的java對象! –

+0

@ArneBurmeister:感謝您的評論,maby astupit問題,但爲什麼?我正在使用Microbridge服務器爲Android手機和帶有USB屏蔽的Arduino之間的adb連接。 – Roy08

相關問題