您将在代理有时间将消息发送回之前关闭客户端。
另外,您不需要2个客户端实例,只需一个实例就可以发送和接收。
我已经稍微修改了您的代码,现在它将继续运行并接收消息,直到您将其杀死。
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;import org.eclipse.paho.client.mqttv3.MqttCallback;import org.eclipse.paho.client.mqttv3.MqttClient;import org.eclipse.paho.client.mqttv3.MqttException;import org.eclipse.paho.client.mqttv3.MqttMessage;public class PahoDemo implements MqttCallback {MqttClient client;public PahoDemo() {}public static void main(String[] args) { new PahoDemo().doDemo();}public void doDemo() { try { client = new MqttClient("tcp://192.168.118.11:1883", "Sending"); client.connect(); client.setCallback(this); client.subscribe("foo"); MqttMessage message = new MqttMessage(); message.setPayload("A single message from my computer fff" .getBytes()); client.publish("foo", message); } catch (MqttException e) { e.printStackTrace(); }}@Overridepublic void connectionLost(Throwable cause) { // TODO Auto-generated method stub}@Overridepublic void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println(message); }@Overridepublic void deliveryComplete(IMqttDeliveryToken token) { // TODO Auto-generated method stub}}
编辑:添加了丢失的内容
client.setCallback(this)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)