我有一个类包含两个具有一些变量的类对象。我想通过带发送功能的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();
}
我的问题是,如果这是一个很好的解决方案或没有?
http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array – Chill
在您对我的回答的评论中,您说接收器将运行在Arduino上?你写的接收器是用Java编写的?我很抱歉,但如果不知道更确切地说明你想要完成的是什么,就很难给出正确的答案。 –