我正在使用mqtt在客户端和服务器之间发送和接收消息。消息以字节的形式发送。我需要在mqtt消息中发送一个类对象。
我尝试将对象序列化为字节,如下所示
deviceloc d=new deviceloc();
d.id=mqttClientId;
d.add=strAddress;
d.lat=loc.getLatitude();
d.lon=loc.getLongitude();
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o=new ObjectOutputStream(b);
o.writeObject(d);
o.close();
byte bytes[]=b.toByteArray();
这里的deviceloc是包com.example.cv_client_android
我发送的信息如下
mqttClient.publish("admin/location",bytes,MQTT_QUALITY_OF_SERVICE,MQTT_RETAINED_PUBLISH);
在服务器端,我收到消息并反序列化,如下所示
public void publishArrived(String topic, byte[] payloadbytes, int qos, boolean retained)
throws Exception {
ByteArrayInputStream b1 = new ByteArrayInputStream(payloadbytes);
ObjectInputStream o1 = new ObjectInputStream(b1);
deviceloc obj1=(deviceloc)o1.readObject();
System.out.println(obj1.id);
System.out.println(obj1.add);
System.out.println(obj1.lat);
System.out.println(obj1.lon);
}
这里的类deviceloc就在包名包中。
在客户端成功发送消息。 T在服务器端出现以下错误,
java.lang.ClassNotFoundException: com.example.cv_client_android.deviceloc
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at pack.Controller.publishArrived(Controller.java:450)
at com.ibm.mqtt.MqttClient.publishArrived(Unknown Source)
at com.ibm.mqtt.MqttBaseClient.process(Unknown Source)
at com.ibm.mqtt.MqttPublish.process(Unknown Source)
at com.ibm.mqtt.Mqtt.process(Unknown Source)
at com.ibm.mqtt.MqttBaseClient.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
帮助我。谢谢!
答案 0 :(得分:0)
反序列化对象的类必须在接收器的CLASSPATH上可用。