MQTT
MQTT의 구현
수색…
java의 publish / subscriber 예제
동적 웹 프로젝트를 sts / eclipse에 작성하면 eclipse paho jar 파일 을 다운로드 하여 webcontent-> webinf-> folder-> lib에 jar 파일 을 다운로드 하여 붙여 넣을 수 있습니다.
게시 예제
String broker = "tcp://localhost:1883";
String topicName = "test/topic";
int qos = 1;
MqttClient mqttClient = new MqttClient(broker,String.valueOf(System.nanoTime()));
//Mqtt ConnectOptions is used to set the additional features to mqtt message
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true); //no persistent session
connOpts.setKeepAliveInterval(1000);
MqttMessage message = new MqttMessage("Ed Sheeran".getBytes());
// here sheeran은 메시지입니다.
message.setQos(qos); //sets qos level 1
message.setRetained(true); //sets retained message
MqttTopic topic2 = mqttClient.getTopic(topicName);
mqttClient.connect(connOpts); //connects the broker with connect options
topic2.publish(message); // publishes the message to the topic(test/topic)
구독 예제
//We're using eclipse paho library so we've to go with MqttCallback
MqttClient client = new MqttClient("tcp://localhost:1883","clientid");
client.setCallback(this);
MqttConnectOptions mqOptions=new MqttConnectOptions();
mqOptions.setCleanSession(true);
client.connect(mqOptions); //connecting to broker
client.subscribe("test/topic"); //subscribing to the topic name test/topic
//Override methods from MqttCallback interface
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("message is : "+message);
}
.
.//other override methods
.
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow