Skip to content

Instantly share code, notes, and snippets.

@kwonghung-YIP
Last active February 24, 2022 05:03
Show Gist options
  • Save kwonghung-YIP/9e7fe31af5ddb65e6b50a0e0688585af to your computer and use it in GitHub Desktop.
Save kwonghung-YIP/9e7fe31af5ddb65e6b50a0e0688585af to your computer and use it in GitHub Desktop.
JMeter BeanShell Example to integrate with Paho Java MQTTv5
import java.nio.charset.StandardCharsets;
import org.eclipse.paho.mqttv5.client.MqttClientPersistence;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.common.MqttSubscription;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
//print("HeHe!");
log.info("HaHa!");
SampleResult.setSuccessful(true);
ResponseCode = "200";
IsSuccess = true;
String brokerUrl = "ws://218.103.73.80:443/mqtt";
String clientId = "jmeter-cli_"+UUID.randomUUID();
String username = "racingtouch";
String password = "00000000";
MqttClientPersistence persistence = new MemoryPersistence();
MqttAsyncClient client = new MqttAsyncClient(brokerUrl, clientId, persistence);
MqttConnectionOptions options = new MqttConnectionOptions();
options.setUserName(username);
options.setPassword(password.getBytes(StandardCharsets.UTF_8));
client.setCallback(new MqttCallback() {
public void mqttErrorOccurred(MqttException exception) {
log.error("MQTT Client error occurred",exception);
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
log.info("message recevied from topic {}", topic);
}
public void disconnected(MqttDisconnectResponse disconnectResponse) {
log.info("MQTT Client disconnected");
}
public void deliveryComplete(IMqttToken token) {
try {
log.info("MQTT Client delivery completed. {} {}",new String(token.getMessage().getPayload(),StandardCharsets.UTF_8), token.getTopics());
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void connectComplete(boolean reconnect, String serverURI) {
log.info("MQTT Client connect completed");
}
public void authPacketArrived(int reasonCode, MqttProperties properties) {
// TODO Auto-generated method stub
}
});
IMqttToken token = client.connect(options);
token.waitForCompletion();
MqttSubscription subscription = new MqttSubscription("#");// hk/d/prdt/wager/evt/01/upd/racing/20140120/#");
token = client.subscribe(subscription);
token.waitForCompletion();
Thread.sleep(15*1000);
client.disconnect();
client.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment