How to send objects instead of string in mqtt messages?

痴心易碎 提交于 2019-12-11 08:36:36

问题


I'm currently using mqtt to communicate between client and server and mqtt publish method takes message as bytes. I need to send latitude, longitude, address,etc in my single mqtt publish and be able to receive those on server side. How can I achieve it?

I'm using wmqtt client library on client side (android) and paho client library on server side (jsp,servlets).

deviceloc d=new deviceloc();
d.id="1234";
d.add="hyder";
d.lat=17.5;
d.lon=78.5;
try {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o=new ObjectOutputStream(b);
o.writeObject(d);
byte bytes[]=b.toByteArray();
MqttMessage data=new MqttMessage(bytes);
ByteArrayInputStream b1 = new ByteArrayInputStream(data.toString().getBytes());
ObjectInputStream o1 = new ObjectInputStream(b1);
Object obj1;
try {
obj1 = o1.readObject();
deviceloc dd=(deviceloc)obj1;
System.out.println(dd.id);
System.out.println(dd.add);
System.out.println(dd.lat);
System.out.println(dd.lon);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
catch(IOException e)
{
e.printStackTrace();
}

I'm getting streamcorrupted exception


回答1:


Serialise your objects to xml (or CSV or Json or roll-your-own format) strings. Form your message from those strings. Send your message as bytes. Reverse the process at the receiving end.



来源:https://stackoverflow.com/questions/22061737/how-to-send-objects-instead-of-string-in-mqtt-messages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!