Websocket or socket is a computer communication protocol, providing full-duplex communication channels over a single TCP connection and MQTT is a lightweight messaging protocol for small sensors and mobile devices.

To make a socket connection in Grails  3 you need to add Spring Websocket plugin in build.gradle under dependencies. (also refer to https://plugins.grails.org/plugin/zyro/grails-spring-websocket for more info about the plugin) and to make MQTT connection you need jms and activemq as an extra dependency.

Then add the below code in your resources.groovy

At last add the following code in any service where you need to publish the message. Broker messaging template is needed to publish the message to the browser and jms service to the mqtt connections.

Note: Don’t forget to inject the brokerMessagingTemplate and jmsService in your service.

Now everything is in the place and we can run our tests.

To test this just install the chrome extension MQTTLens,

  • Make a new connection
    • Add any connection name
    • Add the host name (127.0.0.1) and port(61612)
    • Generate a random id
    • Hit create connection
  • Subscribe to the topic i.e. hello in our case
  • Publish
    • Add topic i.e hello
    • Add any message
    • Hit publish
  • You should see the message on the display screen provided by MQTTLens
  • Run the service code that you added above and you should see the message on the display

Thanks