如何发送的对象,而不是字符串MQTT消息? [英] How to send objects instead of string in mqtt messages?

查看:607
本文介绍了如何发送的对象,而不是字符串MQTT消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用MQTT客户机和服务器之间进行沟通和MQTT发布方法将消息作为字节。我需要发送经度,纬度,地址,等我在单MQTT发布和能够接收到这些服务器端。我怎样才能实现呢?
我使用的客户端(Android)和泛美卫生组织客户端库在服务器端(JSP,servlet的)wmqtt客户端库。

I am 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 am using wmqtt client library on client side (android) and paho client library on server side (jsp,servlets).

在code小的帮助,请。

Little help on code please.

感谢

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();
}

我得到streamcorrupted例外

i am getting streamcorrupted exception

推荐答案

您的序列化对象到XML(或CSV或JSON或滚你自己的格式)字符串。形成了从这些字符串的邮件。发送邮件以字节为单位。在接收端逆转这一过程。

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.

这篇关于如何发送的对象,而不是字符串MQTT消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆