Examples¶
Complete and functional example collection to learn how to use Socket.IO Client in Go.
π Quick Start¶
All examples can be run with a single command:
π Available Examples¶
1. Basic - Basic Connection¶
Location: examples/basic/
Simple example of connection, event emission and reception.
Features: - Connect to Socket.IO server - Emit events to server - Listen to events from server - Handle connection and disconnection
Usage:
Key code:
client := socketio.New("ws://localhost:3000")
client.OnConnect(func() {
client.Emit("hello", "world")
})
client.On("message", func(data ...interface{}) {
fmt.Println("Recibido:", data[0])
})
2. Authentication - JWT Authentication¶
Location: examples/authentication/
Authentication with JWT and custom headers.
Features: - Authentication with JWT token - Custom HTTP headers - Authentication error handling - Re-authentication on reconnect
Usage:
Key code:
client := socketio.New("ws://localhost:3000", socketio.Options{
Auth: map[string]interface{}{
"token": "eyJhbGciOiJIUzI1NiIs...",
},
Headers: map[string]string{
"Authorization": "Bearer token-123",
},
})
3. Binary - Binary Events¶
Location: examples/binary/
File and binary data transfer.
Features: - File upload (images, PDFs, etc.) - File download - Binary data streaming - Checksum validation
Usage:
Key code:
// Leer y enviar archivo
imageData, _ := os.ReadFile("photo.jpg")
client.Of("/").EmitBinary("upload", imageData, map[string]interface{}{
"filename": "photo.jpg",
"size": len(imageData),
})
// Recibir archivo
client.On("file", func(data ...interface{}) {
binaryData := data[0].([]byte)
os.WriteFile("downloaded.jpg", binaryData, 0644)
})
4. Chat - Chat Application¶
Location: examples/chat/
Real-time chat with rooms and users.
Features: - Real-time messaging - Rooms - User notifications (join/leave) - Typing status
Usage:
Key code:
chat := client.Of("/chat")
chat.On("message", func(data ...interface{}) {
user := data[0].(string)
msg := data[1].(string)
fmt.Printf("[%s]: %s\n", user, msg)
})
chat.Emit("join-room", "general")
chat.Emit("message", "juan", "Hola!")
5. Namespaces - Multiple Namespaces¶
Location: examples/namespaces/
Using multiple namespaces for logical separation.
Features: - Default namespace (/) - Custom namespaces - Isolated events per namespace - Independent connection handling
Usage:
Key code:
// Namespace por defecto
client.On("global-event", handler)
// Namespaces personalizados
chat := client.Of("/chat")
chat.On("message", chatHandler)
admin := client.Of("/admin")
admin.On("stats", adminHandler)
6. Acknowledgments - Request-Response¶
Location: examples/acknowledgments/
Request-response pattern with acknowledgments.
Features: - Emit with response (ACK) - Response timeout - Server response handling - Synchronous pattern over asynchronous connection
Usage:
Key code:
client.EmitWithAck("get-user", func(response ...interface{}) {
if response == nil {
fmt.Println("Timeout")
return
}
user := response[0].(map[string]interface{})
fmt.Println("Usuario:", user["name"])
}, "user-123")
7. Reconnection - Resilient Reconnection¶
Location: examples/reconnection/
Advanced automatic reconnection handling.
Features: - Automatic reconnection - Exponential backoff - State re-synchronization - Offline queue
Usage:
Key code:
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 10,
ReconnectDelay: time.Second,
ReconnectDelayMax: 5 * time.Second,
})
client.OnReconnectAttempt(func(attempt int) {
fmt.Printf("Intento #%d\n", attempt)
})
client.OnReconnect(func(attempt int) {
// Re-sincronizar estado
client.Emit("sync-state", lastState)
})
8. Rooms - Rooms and Broadcasting¶
Location: examples/rooms/
Room system for group messaging.
Features: - Join rooms - Leave rooms - Broadcast to specific room - Multiple simultaneous rooms
Usage:
Key code:
client.Emit("join-room", "sala-general")
client.Emit("join-room", "sala-tech")
client.On("room-message", func(data ...interface{}) {
room := data[0].(string)
msg := data[1].(string)
fmt.Printf("[%s] %s\n", room, msg)
})
client.Emit("message-to-room", "sala-tech", "Hola tech!")
π By Difficulty Level¶
Basic Level π’¶
Ideal for getting started:
- Basic - Connection and basic events
- Namespaces - Organization with namespaces
- Rooms - Rooms for groups
Intermediate Level π‘¶
More advanced patterns:
- Authentication - Security and authentication
- Acknowledgments - Request-response pattern
- Reconnection - Network resilience
Advanced Level π΄¶
Complex use cases:
- Binary - File transfer
- Chat - Complete end-to-end application
π οΈ Requirements¶
Socket.IO Server¶
Most examples require a Socket.IO server. You can use the included testserver or any Socket.IO v4 server.
Option 1: Test server (Node.js)
# Instalar Socket.IO
npm install socket.io
# Crear server.js
cat > server.js << 'EOF'
const { Server } = require('socket.io');
const io = new Server(3000);
io.on('connection', (socket) => {
console.log('Cliente conectado');
socket.on('hello', (data) => {
console.log('Recibido:', data);
socket.emit('message', 'Echo: ' + data);
});
});
console.log('Servidor Socket.IO escuchando en puerto 3000');
EOF
# Ejecutar
node server.js
Option 2: Python server
π Example Structure¶
Each example includes:
- README.md - Example-specific documentation
- main.go - Main code
- Comments - Detailed explanations in code
π Useful Links¶
π‘ Tips¶
Run with Verbose¶
Run with Race Detector¶
Customize Server URL¶
Most examples allow configuring the URL:
# Variable de entorno
SERVER_URL=ws://api.example.com go run .
# O editando el cΓ³digo
const serverURL = "ws://localhost:3000"
π€ Contributing¶
Have an interesting example? Open a PR or suggest an idea.
π License¶
All examples are under the same MIT license as the project.