Java标准MQTT服务器推送代码
<p>推送消息内容byteMessage的编码方式,可以参考[Java云喇叭云打印协议编码](<a href="http://doc.szzkc.com/web/#/18?page_id=74">http://doc.szzkc.com/web/#/18?page_id=74</a> "Java云喇叭云打印协议编码")</p>
<pre><code class="language-java"> import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttPublishSample {
public static void main(String[] args) {
String topic = &quot;设备底部标签中IMEI号码&quot;;
String content = &quot;推送内容,参考Java云喇叭云打印协议编码,http://doc.szzkc.com/web/#/18?page_id=74&quot;;
int qos = 2;
String broker = &quot;tcp://MQTT服务器地址:端口&quot;;
String clientId = &quot;自定义&quot;;
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println(&quot;Connecting to broker: &quot;+broker);
sampleClient.connect(connOpts);
System.out.println(&quot;Connected&quot;);
System.out.println(&quot;Publishing message: &quot;+content);
MqttMessage message = new MqttMessage(content.getBytes(&quot;GBK&quot;));
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println(&quot;Message published&quot;);
sampleClient.disconnect();
System.out.println(&quot;Disconnected&quot;);
System.exit(0);
} catch(MqttException me) {
System.out.println(&quot;reason &quot;+me.getReasonCode());
System.out.println(&quot;msg &quot;+me.getMessage());
System.out.println(&quot;loc &quot;+me.getLocalizedMessage());
System.out.println(&quot;cause &quot;+me.getCause());
System.out.println(&quot;excep &quot;+me);
me.printStackTrace();
}
}
}</code></pre>