WebSocket API
TinyMQ features a native WebSocket server (RFC 6455) that allows full-duplex communication over a single, long-lived TCP connection. It operates on the same port as the HTTP server (/ws).
Connection
Connect to the WebSocket endpoint:
ws://localhost:7800/ws
If authentication is enabled, you can provide the API key via the api_key query parameter, or send it in the first message.
ws://localhost:7800/ws?api_key=your_secret_key
Protocol (TMP-WS)
TinyMQ uses a lightweight JSON command protocol over WebSocket.
1. Subscribe to a Topic
To receive messages, send a subscribe command. Subscriptions in WebSocket are non-destructive (Spy Mode). Consuming a message via WebSocket does not dequeue it from the WAL.
Request:
{
"command": "subscribe",
"topic": "sensor.data"
}
Response (when a message arrives):
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"topic": "sensor.data",
"payload": "SGVsbG8gV29ybGQ=",
"payload_text": "Hello World",
"timestamp": "2023-10-01T12:00:00Z"
}
Note:
payloadis always Base64 encoded.payload_textis populated if the content is valid UTF-8.
2. Publish a Message
Request:
{
"command": "publish",
"topic": "sensor.data",
"payload": "SGVsbG8gV29ybGQ="
}
3. Keep-Alive (Ping)
To keep the connection alive behind proxies, send a ping command.
Request:
{
"command": "ping"
}
Response:
{
"status": "pong"
}
Architecture
Go SDK Usage
The official Go SDK includes a robust WebSocket client:
package main
import (
"fmt"
"github.com/x-name15/tinymq/client"
)
func main() {
wsClient := client.NewWSClient("ws://localhost:7800/ws")
wsClient.Connect()
wsClient.Subscribe("test_topic", func(msg client.Message) {
fmt.Printf("Received: %s\n", msg.PayloadText)
})
wsClient.Publish("test_topic", []byte("Hello via WebSocket"))
select{} // Block forever
}