我正在尝试使用org.eclipse.paho.client.mqttv3-1.2.0.jar中的包来实现Pub-Sub
下面的订户代码:
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import java.net.*;
public class Subscriber {
//public static final String BROKER_URL = "tcp://iot.eclipse.org:1883";
public static final String BROKER_URL = "tcp://localhost:1883";
private MqttClient client;
String topic = "Demo Topic";
public static void main(String[] args) {
System.out.println("MQTT Broker: " + BROKER_URL);
new Subscriber();
}
public Subscriber() {
String clientId = getMacAddress() + "-sub";
System.out.println("Client ID = " + clientId);
try {
client = new MqttClient(BROKER_URL, clientId);
client.connect();
client.setCallback(new SubscribeCallback());
client.subscribe(topic);
} catch (MqttException e) {
e.printStackTrace(); System.exit(1);
}
}
public byte[] getMacAddress(){
byte[] mac = new byte[6];
try{
InetAddress address = InetAddress.getLocalHost();
NetworkInterface nwi = NetworkInterface.getByInetAddress(address);
mac = nwi.getHardwareAddress();
System.out.println(mac);
} catch(Exception e) {
System.out.println(e);
}
return mac;
}
}
class SubscribeCallback implements MqttCallback {
@Override
public void connectionLost (Throwable cause) { }
@Override
public void messageArrived (String topic, MqttMessage message) {
System.out.println("Message arrived. Topic: " + topic
+ " Message: " + message.toString());
if ("I'm gone".equals(topic)) {
System.out.println("Sensor gone!");
}
}
@Override
public void deliveryComplete (IMqttDeliveryToken token) { }
}
我通过执行以下命令创建了.class文件
javac -cp org.eclipse.paho.client.mqttv3-1.2.0.jar Subscriber.java
类文件已创建,没有任何错误。接下来,我尝试通过以下方式运行Subscriber类
java -cp org.eclipse.paho.client.mqttv3-1.2.0.jar Subscriber
我收到订户未找到的类的异常
Error: Could not find or load main class Subscriber
Caused by: java.lang.ClassNotFoundException: Subscriber
注意:Subscriber.java和org.eclipse.paho.client.mqttv3-1.2.0.jar都在同一目录中
答案 0 :(得分:0)
您还需要将当前目录添加到类路径中
java -cp .:org.eclipse.paho.client.mqttv3-1.2.0.jar Subscriber
如果在Windows上运行,则将:
的{{1}}更改为