Files
antrean-anjungan/examples/server/server-initiated-broadcasts.go
2025-09-18 19:01:22 +07:00

88 lines
2.8 KiB
Go

package main
import (
"fmt"
"log"
"api-service/internal/config"
"api-service/internal/database"
v1 "api-service/internal/routes/v1"
)
func main() {
// Load configuration
cfg := config.LoadConfig()
cfg.Validate()
// Initialize database service
dbService := database.New(cfg)
_ = dbService // Mark as used to avoid compiler warning
// Create router
router := v1.RegisterRoutes(cfg)
// Get WebSocket handler from the router (this is a simplified example)
// In a real application, you'd inject the handler or use dependency injection
fmt.Println("WebSocket Server Example with Server-Initiated Broadcasts")
fmt.Println("========================================================")
fmt.Println()
fmt.Println("This example demonstrates how to broadcast messages from the server")
fmt.Println("to all connected WebSocket clients.")
fmt.Println()
fmt.Println("Features demonstrated:")
fmt.Println("- Broadcasting messages to all clients")
fmt.Println("- Broadcasting to specific rooms")
fmt.Println("- Periodic heartbeat messages")
fmt.Println("- Simulated data streaming")
fmt.Println()
fmt.Println("To test:")
fmt.Println("1. Start the Go API server: go run cmd/api/main.go")
fmt.Println("2. Start the Nuxt 3 client: cd examples/nuxt3-websocket-client && npm run dev")
fmt.Println("3. Open browser at http://localhost:3001")
fmt.Println("4. You should see connection status and incoming messages")
fmt.Println()
fmt.Println("The server will automatically send:")
fmt.Println("- Welcome message on connection")
fmt.Println("- Heartbeat messages every 30 seconds")
fmt.Println("- Simulated data every 10 seconds")
fmt.Println()
fmt.Println("You can also send messages from the client to the server.")
fmt.Println()
// Start server
fmt.Println("Starting server on :8080...")
log.Fatal(router.Run(":8080"))
}
// Example of how to broadcast messages programmatically
// This would typically be called from your business logic
func exampleBroadcasts() {
// This is pseudo-code showing how you would use the WebSocket handler
// In a real application, you'd get the handler instance from your dependency injection
/*
// Broadcast to all clients
websocketHandler.BroadcastMessage("announcement", map[string]interface{}{
"title": "System Update",
"message": "The system will be updated in 5 minutes",
})
// Broadcast to a specific room
websocketHandler.BroadcastToRoom("admin", "notification", map[string]interface{}{
"level": "warning",
"message": "Admin action required",
})
// Send to specific client
websocketHandler.SendToClient(clientID, "private", map[string]interface{}{
"message": "This is a private message",
})
// Start periodic broadcasts
websocketHandler.StartPeriodicBroadcast(30 * time.Second)
// Start simulated data stream
websocketHandler.SimulateDataStream()
*/
}