Skip to content

Instantly share code, notes, and snippets.

@codepope
Last active December 24, 2015 15:49
Show Gist options
  • Save codepope/6823771 to your computer and use it in GitHub Desktop.
Save codepope/6823771 to your computer and use it in GitHub Desktop.
class CountingResourceHandler extends ResourceHandler {
int req_count=0;
MqttClient client;
public CountingResourceHandler() {
super();
}
@Override
public void doStart() throws Exception {
super.doStart();
// Create the MqttClient connection to the broker
client=new MqttClient("tcp://localhost:1883","countingjetty");
client.connect();
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
super.handle(target, baseRequest, request, response);
// Increment the count
req_count++;
try {
// Publish to the broker with a QoS of 0 but retained
client.publish("countingjetty/handlerequest",Integer.toString(req_count).getBytes(),0,true );
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void doStop() throws Exception {
super.doStop();
// Cleanly stop the Mqtt client connection
client.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment