Skip to main content

Overview

The Invernaderos API uses STOMP (Simple Text Oriented Messaging Protocol) over WebSocket to provide real-time sensor data streaming to connected clients. This setup includes SockJS fallback for browsers that don’t support native WebSocket.

WebSocket Endpoints

ws://your-host:8080/ws/greenhouse

Endpoint Configuration

The API provides two endpoints:
  • /ws/greenhouse - Primary endpoint with SockJS fallback support for maximum compatibility
  • /ws/greenhouse-native - Native WebSocket endpoint without SockJS overhead
SockJS Fallback: When WebSocket is unavailable, SockJS automatically falls back to HTTP-based transports (XHR streaming, XHR polling, etc.) ensuring connectivity across all environments.

Connection Setup

1

Install Required Libraries

Add the STOMP.js and SockJS client libraries to your project:
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@stomp/stompjs@7/bundles/stomp.umd.min.js"></script>
2

Initialize SockJS Connection

Create a SockJS socket instance pointing to the WebSocket endpoint:
const socket = new SockJS('http://localhost:8080/ws/greenhouse');
Protocol: Use http:// (not ws://) when connecting to SockJS endpoints. SockJS handles the protocol upgrade internally.
3

Create STOMP Client

Wrap the SockJS socket with a STOMP client:
const stompClient = Stomp.over(socket);
This creates a STOMP protocol layer on top of the WebSocket/SockJS connection.
4

Connect to Broker

Establish the STOMP connection with the message broker:
stompClient.connect({}, function(frame) {
  console.log('Connected: ' + frame);
  
  // Connection successful - ready to subscribe to topics
});
The empty object {} can contain connection headers like authentication tokens if needed:
stompClient.connect(
  { Authorization: 'Bearer YOUR_TOKEN' },
  onConnectCallback,
  onErrorCallback
);

Complete JavaScript Example

const socket = new SockJS('http://localhost:8080/ws/greenhouse');
const stompClient = Stomp.over(socket);

stompClient.connect({}, function(frame) {
  console.log('Connected to WebSocket');
  
  // Subscribe to messages topic
  stompClient.subscribe('/topic/greenhouse/messages', function(message) {
    const data = JSON.parse(message.body);
    console.log('Received sensor data:', data);
    
    // Process sensor data
    updateDashboard(data);
  });
});

Configuration Details

Message Broker Settings

The API uses an in-memory simple message broker with the following configuration:
override fun configureMessageBroker(registry: MessageBrokerRegistry) {
    // Enable simple in-memory broker
    registry.enableSimpleBroker("/topic", "/queue")
    
    // Prefix for @MessageMapping annotated methods
    registry.setApplicationDestinationPrefixes("/app")
    
    // Prefix for user-specific messages
    registry.setUserDestinationPrefix("/user")
}

Destination Prefixes

PrefixPurposeExample
/topicBroadcast messages (one-to-many)/topic/greenhouse/messages
/queuePoint-to-point messages/queue/notifications
/appApplication-bound messages/app/sensor/update
/userUser-specific messages/user/alerts

CORS Configuration

The WebSocket endpoints allow connections from all origins in development:
registry.addEndpoint("/ws/greenhouse")
    .setAllowedOriginPatterns("*") // Allow all origins
    .withSockJS()
Production Security: In production environments, restrict allowedOriginPatterns to specific domains:
.setAllowedOriginPatterns(
  "https://yourdomain.com",
  "https://app.yourdomain.com"
)

Connection Lifecycle

1

Connection Establishment

Client initiates SockJS connection → Protocol negotiation → WebSocket upgrade (if available)
2

STOMP Handshake

STOMP CONNECT frame sent → Server responds with CONNECTED frame
3

Active Session

Client can subscribe to topics and send/receive messages
4

Disconnection

Clean disconnect with DISCONNECT frame or connection timeout

Troubleshooting

Verify the endpoint URL is correct:
  • Use http:// protocol (not ws://) for SockJS endpoints
  • Check that the API server is running and accessible
  • Verify the port number (default: 8080)
Ensure you’ve subscribed to the correct topic:
stompClient.subscribe('/topic/greenhouse/messages', callback);
Check that sensor data is being published to the topic.
  • Check network stability
  • Implement reconnection logic with exponential backoff
  • Consider using heartbeats to keep connection alive:
stompClient.heartbeat.outgoing = 20000; // 20 seconds
stompClient.heartbeat.incoming = 20000;
CORS is configured on the server side. If you encounter CORS issues:
  1. Verify the server’s allowedOriginPatterns includes your domain
  2. Check that your frontend uses the correct protocol (http/https)
  3. Ensure credentials are not required (or properly configured)

Next Steps

WebSocket Topics

Learn about available topics and message formats

API Reference

Explore WebSocket API endpoints

Build docs developers (and LLMs) love