Skip to content

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:

cd examples/[example-name]
go run .

πŸ“š 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:

cd examples/basic
go run .

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:

cd examples/authentication
go run .

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:

cd examples/binary
go run .

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:

cd examples/chat
go run .

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:

cd examples/namespaces
go run .

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:

cd examples/acknowledgments
go run .

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:

cd examples/reconnection
go run .

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:

cd examples/rooms
go run .

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:

  1. Basic - Connection and basic events
  2. Namespaces - Organization with namespaces
  3. Rooms - Rooms for groups

Intermediate Level 🟑

More advanced patterns:

  1. Authentication - Security and authentication
  2. Acknowledgments - Request-response pattern
  3. Reconnection - Network resilience

Advanced Level πŸ”΄

Complex use cases:

  1. Binary - File transfer
  2. 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

pip install python-socketio
python testserver/server.py

πŸ“– Example Structure

Each example includes:

  • README.md - Example-specific documentation
  • main.go - Main code
  • Comments - Detailed explanations in code


πŸ’‘ Tips

Run with Verbose

go run . -v

Run with Race Detector

go run -race .

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.