Pradeep Singh | 11th Jan 2017
MQTT is a lightweight publish/subscribe messaging protocol which suits best for low power sensors. Whereas, WebSocket is a transport layer protocol, designed to be TCP for the Web. It (WebSocket) provides full-duplex communication channels over a single TCP connection between Client and Server.
Bringing these two protocols together can open an ocean of possibilities in the world of IoT. Imagine a HTML page that can display live sensor data without refreshing or polling Web Server periodically. Sounds interesting?
Most of the MQTT Brokers now support WebSocket communication; which means all you need to do is write Client side code and leverage MQTT Broker to cover everything else.
Let’s try to a write a simple HTML 5 Web Page that can send and recieve MQTT messages over WebSocket.
If you have a local MQTT Broker that supports WebSockets; feel free to use it. Otherwise, there are several Cloud based MQTT Brokers which can be used for testing purpose. Here in this article we are going to use HiveMQ Public MQTT Broker (For more details on this please visit http://www.hivemq.com/try-out/).
Following is the WebSocket URL for HiveMQ Test Server –
Web Page (The Code):
I have written a sample WebPage that can be used for testing MQTT over WebSockets. You can download HTML code from GitHub Repository . You can run this code directly on your machine. Make sure your internet connection is working in case you want to use cloud based MQTT Broker (such as HiveMQ – ws://broker.hivemq.com:8000/mqtt).
Following diagram shows a simplified view of information flow between this sample HTML Page and MQTT Broker.
Feel free to tweak the code and use it in your IoT projects. Cheers!!!
How can I set up a web page client to use TLS over websockets?
thanks in advance,
Very useful tutorials, great work.