Skip to content

Getting Started Guide

This guide will help you start using the Socket.IO client for Go in less than 5 minutes.

Installation

Requires Go 1.18 or higher.

go get github.com/arcaela/socket.io-client-go

Your First Connection

Create a main.go file with the following code:

package main

import (
  "fmt"
  socketio "github.com/arcaela/socket.io-client-go"
)

func main() {
  // Crear cliente
  client := socketio.New("ws://localhost:3000")
  defer client.Close()

  // Manejar conexión exitosa
  client.OnConnect(func() {
    fmt.Println("✅ Conectado al servidor")
  })

  // Manejar desconexión
  client.OnDisconnect(func(reason string) {
    fmt.Printf("❌ Desconectado: %s\n", reason)
  })

  // Escuchar evento del servidor
  client.On("welcome", func(data ...interface{}) {
    fmt.Printf("📩 Mensaje del servidor: %v\n", data[0])
  })

  // Emitir evento al servidor
  client.Emit("hello", "¡Hola desde Go!")

  // Mantener la aplicación ejecutándose
  select {}
}

Run your application:

go run main.go

Core Concepts

Socket

The Socket is the main client that manages the connection to the Socket.IO server. It's created with socketio.New() and provides methods to emit and listen for events.

client := socketio.New("ws://localhost:3000")

Events

Events are messages sent between client and server. You can listen for events with On() and emit events with Emit().

// Listen
client.On("message", func(data ...interface{}) {
  fmt.Println(data[0])
})

// Emit
client.Emit("message", "Hello world")

Namespaces

Namespaces allow you to multiplex connections over a single WebSocket connection. The default namespace is /.

// Default namespace
client.On("news", handler)

// Custom namespace
chat := client.Of("/chat")
chat.On("message", handler)

Lifecycle

The connection has several states you can monitor:

client.OnConnect(func() {
  fmt.Println("Connected")
})

client.OnDisconnect(func(reason string) {
  fmt.Println("Disconnected:", reason)
})

client.OnError(func(err error) {
  fmt.Println("Error:", err)
})

Basic Configuration

You can customize the client's behavior with options:

client := socketio.New("ws://localhost:3000", socketio.Options{
  // Authentication
  Auth: map[string]interface{}{
    "token": "your-secret-token",
  },

  // Auto-reconnection
  ReconnectAttempts: 5,
  ReconnectDelay:    time.Second,
  ReconnectDelayMax: 5 * time.Second,

  // Timeouts
  Timeout:    30 * time.Second,
  AckTimeout: 5 * time.Second,
})

Common Patterns

Emit with Response (Acknowledgment)

client.EmitWithAck("request", func(response ...interface{}) {
  fmt.Println("Server response:", response[0])
}, "request data")

Handling Reconnection

client.OnReconnectAttempt(func(attempt int) {
  fmt.Printf("Reconnection attempt #%d\n", attempt)
})

client.OnReconnectError(func(err error) {
  fmt.Println("Reconnection error:", err)
})

client.OnReconnectFailed(func() {
  fmt.Println("Reconnection failed after all attempts")
})

Check Connection Status

if client.IsConnected() {
  fmt.Println("Client is connected")
}

state := client.GetState()
// state can be: StateDisconnected, StateConnecting, StateConnected, etc.

Next Steps

Now that you have a basic connection working, explore:

Complete Examples

The repository includes complete examples in the examples/ folder:

  • examples/basic/ - Basic connection and events
  • examples/authentication/ - JWT authentication
  • examples/chat/ - Real-time chat application
  • examples/namespaces/ - Multiple namespaces
  • examples/reconnection/ - Reconnection handling

Each example can be run with a single command:

cd examples/basic
go run .