Real-time Communication
Build responsive, interactive applications with Fiberwise's WebSocket-based real-time communication system. Enable live updates, instant feedback, and dynamic user experiences across your platform.
What is Real-time Communication?
Fiberwise provides a comprehensive WebSocket-based communication system that enables real-time data flow between your applications, agents, and users. This system powers live activation updates, instant notifications, and dynamic UI responses.
🔄 Live Activation Updates
Watch agent activations execute in real-time with progress updates, status changes, and live result streaming.
📡 Per-App Connections
Isolated WebSocket connections for each app instance with automatic routing and message filtering.
📢 Event Broadcasting
Broadcast system-wide events, user notifications, and custom messages with targeted delivery.
🔒 Secure Channels
Authenticated WebSocket connections with user isolation and permission-based message routing.
WebSocket Architecture
Connection Flow
1. Connection
Client establishes authenticated WebSocket connection with app context
2. Registration
Connection registered with user ID, app context, and permission scope
3. Message Routing
Messages routed based on user permissions and app isolation
4. Live Updates
Real-time delivery of activation updates and system events
Message Types
Frontend Integration
JavaScript WebSocket Client
// fiberwise-websocket.js
class FiberwiseWebSocket {
constructor(appSlug, authToken) {
this.appSlug = appSlug;
this.authToken = authToken;
this.socket = null;
this.listeners = {};
}
connect() {
const wsUrl = `ws://localhost:7001/ws/${this.appSlug}?token=${this.authToken}`;
this.socket = new WebSocket(wsUrl);
this.socket.onopen = () => {
console.log('WebSocket connected');
this.emit('connected');
};
this.socket.onmessage = (event) => {
const message = JSON.parse(event.data);
this.handleMessage(message);
};
this.socket.onclose = () => {
console.log('WebSocket disconnected');
this.emit('disconnected');
this.reconnect();
};
this.socket.onerror = (error) => {
console.error('WebSocket error:', error);
this.emit('error', error);
};
}
handleMessage(message) {
const { type } = message;
// Emit specific event type
this.emit(type, message);
// Emit generic message event
this.emit('message', message);
}
// Subscribe to specific message types
on(eventType, callback) {
if (!this.listeners[eventType]) {
this.listeners[eventType] = [];
}
this.listeners[eventType].push(callback);
}
emit(eventType, data) {
const callbacks = this.listeners[eventType] || [];
callbacks.forEach(callback => callback(data));
}
// Send message to server
send(message) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(message));
}
}
reconnect() {
setTimeout(() => {
console.log('Attempting to reconnect...');
this.connect();
}, 5000);
}
}
// Usage in app
const ws = new FiberwiseWebSocket('my-app', userToken);
// Listen for activation updates
ws.on('activation_update', (event) => {
updateActivationProgress(event.activation_id, event.progress);
});
// Listen for notifications
ws.on('notification', (notification) => {
showNotification(notification.title, notification.message);
});
ws.connect();
Web Component Integration
// live-activation-status.js
class LiveActivationStatus extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.activationId = this.getAttribute('activation-id');
}
connectedCallback() {
this.render();
this.setupWebSocket();
}
setupWebSocket() {
// Get WebSocket instance from app
const ws = window.fiberwiseWS;
ws.on('activation_update', (event) => {
if (event.activation_id === this.activationId) {
this.updateStatus(event);
}
});
}
updateStatus(event) {
const progressBar = this.shadowRoot.querySelector('.progress-bar');
const statusText = this.shadowRoot.querySelector('.status-text');
const stepText = this.shadowRoot.querySelector('.step-text');
progressBar.style.width = `${event.progress * 100}%`;
statusText.textContent = event.status;
stepText.textContent = event.current_step;
// Update status class
const container = this.shadowRoot.querySelector('.status-container');
container.className = `status-container status-${event.status}`;
}
render() {
this.shadowRoot.innerHTML = `
Initializing...
Preparing activation
`;
}
}
customElements.define('live-activation-status', LiveActivationStatus);
Backend Integration
Agent Integration
# content_generator.py
from fiberwise_sdk import FiberAgent
class ContentGenerator(FiberAgent):
def run_agent(self, input_data, websocket_service=None):
# Send progress updates during execution
if websocket_service:
websocket_service.send_activation_update(
activation_id=self.activation_id,
status="running",
progress=0.1,
current_step="Analyzing input"
)
# Process the request
topic = input_data.get('topic', '')
if websocket_service:
websocket_service.send_activation_update(
activation_id=self.activation_id,
status="running",
progress=0.5,
current_step="Generating content"
)
# Generate content using LLM
content = self._generate_content(topic)
# Send completion update
if websocket_service:
websocket_service.send_activation_update(
activation_id=self.activation_id,
status="completed",
progress=1.0,
current_step="Content generation complete"
)
return {"content": content, "status": "success"}
Custom Event Broadcasting
# app_logic.py
from fiberwise_sdk import get_websocket_service
async def update_user_preferences(user_id, preferences):
# Update preferences in database
await update_preferences_db(user_id, preferences)
# Broadcast update to user's active connections
ws_service = get_websocket_service()
await ws_service.send_to_user(
user_id=user_id,
message={
"type": "preferences_updated",
"data": preferences,
"timestamp": datetime.now().isoformat()
}
)
async def broadcast_system_announcement(message, level="info"):
"""Broadcast announcement to all connected users"""
ws_service = get_websocket_service()
await ws_service.broadcast_all(
message={
"type": "system_announcement",
"level": level,
"message": message,
"timestamp": datetime.now().isoformat()
}
)
Practical Examples
📊 Live Dashboard Updates
Real-time dashboard with metrics and status indicators that update automatically.
// dashboard-metrics.js
ws.on('metrics_update', (data) => {
document.getElementById('active-users').textContent = data.active_users;
document.getElementById('processing-jobs').textContent = data.processing_jobs;
updateChart('performance-chart', data.performance_metrics);
});
💬 Live Chat Integration
Real-time chat system with message delivery and typing indicators.
// chat-component.js
ws.on('new_message', (message) => {
appendMessageToChat(message);
});
ws.on('user_typing', (event) => {
showTypingIndicator(event.user_name);
});
🔔 Notification System
Toast notifications that appear instantly when events occur.
// notification-handler.js
ws.on('notification', (notification) => {
showToast(
notification.title,
notification.message,
notification.level
);
});
📁 File Upload Progress
Live progress tracking for file uploads and processing.
// file-upload-progress.js
ws.on('upload_progress', (event) => {
const progressBar = document.getElementById(`upload-${event.file_id}`);
progressBar.style.width = `${event.progress}%`;
progressBar.textContent = `${Math.round(event.progress)}%`;
});
Configuration & Best Practices
WebSocket Configuration
# app_manifest.yaml
app:
name: My Real-time App
realtime:
enabled: true
max_connections: 1000
message_rate_limit: 100 # messages per minute
heartbeat_interval: 30 # seconds
# Event subscriptions
subscribe_to:
- "activation_updates"
- "system_notifications"
- "data_changes"
# Custom event channels
custom_channels:
- name: "user_chat"
permissions: ["chat:read", "chat:write"]
- name: "admin_alerts"
permissions: ["admin:read"]
Best Practices
🔒 Security Considerations
- Always authenticate WebSocket connections
- Validate user permissions for message access
- Rate limit messages to prevent abuse
- Sanitize data before broadcasting
⚡ Performance Optimization
- Batch multiple updates when possible
- Use message filtering to reduce bandwidth
- Implement connection pooling for scaling
- Monitor connection counts and resource usage
🛠️ Error Handling
- Implement automatic reconnection logic
- Handle connection timeouts gracefully
- Log WebSocket errors for debugging
- Provide fallback for non-real-time users
Next Steps
Ready to build real-time features? Explore these resources: