Introduction
Configuration
Language Support
AMQP 0-9-1 Overview
More Exchange Types
More Consumer Features
Queue Deep-dive
Other Features
Reliable Message Delivery
High Availability
Monitoring
Management HTTP API
Tutorials
Networking
LavinMQ CLI
Websockets with LavinMQ
This tool provides a quick and easy way to test websockets with LavinMQ. Feel free to customize to suit your needs!
Websocket Testing over AMQP
To help you get started with AMQP over Websockets, here’s a simple HTML tool you can use to test sending and receiving messages. This tool uses AMQPWebSocketClient
from the amqp-client.js
library, which can be found on Github. You can find Installation instructions in the README of the repository.
How to Use
-
Include the AMQP WebSocket Client Library The provided HTML tool uses the
AMQPWebSocketClient
library. Ensure the library is available in your project. For example, if you are hosting the library locally, ensure the following line in the<head>
section points to the correct path:<script type="module"> import { AMQPWebSocketClient } from './js/lib/amqp-websocket-client.mjs' </script>
Alternatively, you can use a CDN:
<script src="https://cdn.jsdelivr.net/npm/@cloudamqp/amqp-client@3.2.1/lib/cjs/index.min.js"></script>
-
Save the HTML Code Save the provided code as an HTML file (e.g.,
amqp-websocket-tool.html
). -
Run Your LavinMQ Instance Ensure your LavinMQ instance is running and accessible via Websockets. Don’t forget to update the
url
variable in the script to match your websocket endpoint.const url = "wss://your-websocket-endpoint";
-
Open the HTML File in Your Browser Open the saved HTML file in your browser. The tool will automatically connect to the Websocket endpoint and subscribe to the
amq.fanout
exchange. -
Send and Receive Messages
- Enter a message in the input field and click “Send” to publish it to the
amq.fanout
exchange. - Any messages received on the
amq.fanout
exchange will appear in the textarea.
- Enter a message in the input field and click “Send” to publish it to the
Example Code
<!DOCTYPE html>
<html>
<head>
<script type="module">
import { AMQPWebSocketClient } from './js/lib/amqp-websocket-client.mjs'
const textarea = document.getElementById("textarea")
const input = document.getElementById("message")
const submit = document.getElementById("submit")
const offlineQueue = []
const tls = window.location.protocol === "https:"
const url = `${tls ? "wss" : "ws"}://${window.location.host}` // Update to match your websocket endpoint
const amqp = new AMQPWebSocketClient(url, "/", "guest", "guest")
amqp.onerror = (err) => {
console.log("amqp error", err, "restarting")
start()
}
async function start() {
submit.disabled = true
try {
const conn = await amqp.connect()
const ch = await conn.channel()
const q = await ch.queue("")
await q.bind("amq.fanout")
await q.subscribe({noAck: false}, (msg) => {
textarea.value += msg.bodyString() + "\n"
msg.ack()
})
attachPublish(ch)
while (offlineQueue.length > 0) {
const msg = offlineQueue.shift()
await publish(ch, msg)
}
} catch (err) {
console.error("Error", err, "reconnecting in 1s")
setTimeout(start, 1000)
}
}
function attachPublish(ch) {
document.forms[0].onsubmit = async (e) => {
e.preventDefault()
try {
await publish(ch, input.value)
} catch (err) {
console.error("Could not publish", err)
offlineQueue.push(input.value)
}
input.value = ""
}
submit.disabled = false
}
async function publish(ch, message) {
await ch.basicPublish("amq.fanout", "", message, { contentType: "text/plain" })
}
start()
</script>
</head>
<body>
<form>
<textarea id="textarea" rows=10></textarea>
<br/>
<input id="message" placeholder="Enter your message here"/>
<button id="submit" type="submit">Send</button>
</form>
</body>
</html>
Websocket testing over MQTT
To help you get started with MQTT over Websockets, here’s a simple HTML tool you can use to test sending and receiving messages. This tool uses the Paho MQTT JavaScript library.
-
Install the Paho MQTT JavaScript Library The provided HTML tool uses the Paho MQTT JavaScript library. You need to include the library in your project. You can download the library from the Paho MQTT GitHub repository or use a CDN. For example, if you are hosting the library locally, ensure the following line in the
<head>
section points to the correct path:<script src="/js/lib/paho-mqtt.js" type="text/javascript"></script>
Alternatively, you can use a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.1.0/paho-mqtt.min.js" type="text/javascript"></script>
-
Save the HTML Code Save the provided code as an HTML file (e.g.
mqtt-websocket-tool.html
). -
Run Your LavinMQ Instance Ensure your LavinMQ instance is running and accessible via Websockets. Don’t forget to update the
Paho.Client
initialization in the script with the hostname and port of your websocket endpoint -
Open the HTML File in Your Browser Open the saved HTML file in your browser. The tool will automatically connect to the Websocket endpoint and subscribe to the
ws-mqtt
topic. -
Send and Receive Messages
- Enter a message in the input field and click “Send” to publish it to the
ws-mqtt
topic. - Any messages received on the
ws-mqtt
topic will appear in the textarea.
- Enter a message in the input field and click “Send” to publish it to the
Example Code
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.1.0/paho-mqtt.min.js" type="text/javascript"></script>
</head>
<body>
<form>
<textarea id="textarea" rows=10></textarea>
<br/>
<input id="message" placeholder="Enter your message here"/>
<button id="submit" type="submit">Send</button>
</form>
<script>
const textarea = document.getElementById("textarea");
const input = document.getElementById("message");
const submit = document.getElementById("submit");
// Create a client instance, inut the websocket-endpoint hostname and port.
const client = new Paho.Client(hostName, port, `clientId-${Math.round(Math.random() * 100000)}`)
// Set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// Connect the client
client.connect({ onSuccess: onConnect, userName: "guest", password: "guest" });
// Called when the client connects
function onConnect() {
console.log("Connected to MQTT over Websockets");
client.subscribe("ws-mqtt");
attachPublish();
}
// Called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("Connection lost:", responseObject.errorMessage);
submit.disabled = true;
}
}
// Called when a message arrives
function onMessageArrived(message) {
textarea.value += message.payloadString + "\n";
}
// Attach publish functionality to the form
function attachPublish() {
document.forms[0].onsubmit = (e) => {
e.preventDefault();
try {
client.publish("ws-mqtt", input.value);
} catch (err) {
console.error("Could not publish message:", err);
}
input.value = "";
};
submit.disabled = false;
}
</script>
</body>
</html>
Ready to take the next steps? Here are some things you should keep in mind:
Managed LavinMQ instance on CloudAMQP
LavinMQ has been built with performance and ease of use in mind - we've benchmarked a throughput of about 1,000,000 messages/sec. You can try LavinMQ without any installation hassle by creating a free instance on CloudAMQP. Signing up is a breeze.
Help and feedback
We welcome your feedback and are eager to address any questions you may have about this piece or using LavinMQ. Join our Slack channel to connect with us directly. You can also find LavinMQ on GitHub.