Skip to content

Socket API Reference

The Socket type is the main client that handles the connection to the Socket.IO server.

Table of Contents

Creation

New

func New(rawURL string, options ...Options) *Socket

Creates a new Socket instance and establishes the connection to the server.

Parameters: - rawURL (string): Socket.IO server URL. Can use ws:// or http:// scheme (will be automatically converted to WebSocket) - options (Options, optional): Client configuration

Returns: - *Socket: Client instance

Example:

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

// With options
client := socketio.New("ws://localhost:3000", socketio.Options{
  Auth: map[string]interface{}{
    "token": "abc123",
  },
  ReconnectAttempts: 5,
  Timeout: 30 * time.Second,
})

Connection Methods

Close

func (s *Socket) Close() error

Closes the connection to the server and releases all resources.

Returns: - error: Error if the operation fails

Example:

defer client.Close()

// Or manually
if err := client.Close(); err != nil {
  fmt.Printf("Error closing: %v\n", err)
}

Event Methods

On

func (s *Socket) On(event string, handler EventHandler)

Registers a handler to listen for a specific event on the default namespace (/).

Parameters: - event (string): Event name - handler (EventHandler): Function to execute when the event is received

Example:

client.On("message", func(data ...interface{}) {
  fmt.Printf("Message: %v\n", data[0])
})

client.On("user-joined", func(data ...interface{}) {
  username := data[0].(string)
  fmt.Printf("%s joined\n", username)
})

OnConnect

func (s *Socket) OnConnect(handler func())

Registers a handler that executes when the connection is successfully established.

Parameters: - handler (func()): Function to execute on connection

Example:

client.OnConnect(func() {
  fmt.Println("Connected")
  client.Emit("join-room", "room-1")
})

OnDisconnect

func (s *Socket) OnDisconnect(handler func(reason string))

Registers a handler that executes when the connection is closed.

Parameters: - handler (func(reason string)): Function that receives the disconnection reason

Example:

client.OnDisconnect(func(reason string) {
  fmt.Printf("Disconnected: %s\n", reason)

  if reason == "io server disconnect" {
    fmt.Println("Server closed the connection")
  }
})

OnError

func (s *Socket) OnError(handler func(err error))

Registers a handler that executes when an error occurs.

Parameters: - handler (func(err error)): Function that receives the error

Example:

client.OnError(func(err error) {
  fmt.Printf("Error: %v\n", err)
})

OnReconnectAttempt

func (s *Socket) OnReconnectAttempt(handler func(attempt int))

Registers a handler that executes before each reconnection attempt.

Parameters: - handler (func(attempt int)): Function that receives the attempt number

Example:

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

OnReconnect

func (s *Socket) OnReconnect(handler func(attempt int))

Registers a handler that executes when reconnection is successful.

Parameters: - handler (func(attempt int)): Function that receives the number of attempts it took to reconnect

Example:

client.OnReconnect(func(attempt int) {
  fmt.Printf("Reconnected after %d attempts\n", attempt)
})

OnReconnectError

func (s *Socket) OnReconnectError(handler func(err error))

Registers a handler that executes when a reconnection attempt fails.

Parameters: - handler (func(err error)): Function that receives the error

Example:

client.OnReconnectError(func(err error) {
  fmt.Printf("Reconnection error: %v\n", err)
})

OnReconnectFailed

func (s *Socket) OnReconnectFailed(handler func())

Registers a handler that executes when all reconnection attempts fail.

Parameters: - handler (func()): Function to execute when reconnection fails definitively

Example:

client.OnReconnectFailed(func() {
  fmt.Println("Failed to reconnect")
  notifyUser("Connection lost")
})

Emission Methods

Emit

func (s *Socket) Emit(event string, data ...interface{}) error

Emits an event to the server on the default namespace (/).

Parameters: - event (string): Event name - data (...interface{}): Arguments to send (can be multiple)

Returns: - error: Error if the operation fails

Example:

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

// Multiple arguments
client.Emit("user-action", "login", map[string]interface{}{
  "username": "john",
  "timestamp": time.Now().Unix(),
})

// Handle error
if err := client.Emit("important", data); err != nil {
  fmt.Printf("Error emitting: %v\n", err)
}

EmitWithAck

func (s *Socket) EmitWithAck(event string, ack AckCallback, data ...interface{}) error

Emits an event and waits for an acknowledgment response from the server.

Parameters: - event (string): Event name - ack (AckCallback): Callback function that receives the response - data (...interface{}): Arguments to send

Returns: - error: Error if the operation fails

Example:

client.EmitWithAck("get-user", func(response ...interface{}) {
  if len(response) == 0 {
    fmt.Println("No response received (timeout)")
    return
  }

  user := response[0].(map[string]interface{})
  fmt.Printf("User: %v\n", user)
}, "user-123")

// With configured timeout
client := socketio.New("ws://localhost:3000", socketio.Options{
  AckTimeout: 5 * time.Second,
})

client.EmitWithAck("slow-operation", func(response ...interface{}) {
  if response == nil {
    fmt.Println("Timeout: server did not respond in time")
    return
  }
  fmt.Println("Response:", response[0])
}, "data")

State Methods

IsConnected

func (s *Socket) IsConnected() bool

Returns whether the client is currently connected to the server.

Returns: - bool: true if connected, false otherwise

Example:

if client.IsConnected() {
  client.Emit("ping")
} else {
  fmt.Println("No connection")
}

GetState

func (s *Socket) GetState() ConnectionState

Returns the current connection state.

Returns: - ConnectionState: Current connection state

Possible states: - StateDisconnected (0): Not connected - StateConnecting (1): Establishing connection - StateConnected (2): Connected - StateReconnecting (3): Attempting to reconnect - StateDisconnecting (4): Closing connection

Example:

state := client.GetState()

switch state {
case socketio.StateDisconnected:
  fmt.Println("Disconnected")
case socketio.StateConnecting:
  fmt.Println("Connecting...")
case socketio.StateConnected:
  fmt.Println("Connected")
case socketio.StateReconnecting:
  fmt.Println("Reconnecting...")
case socketio.StateDisconnecting:
  fmt.Println("Disconnecting...")
}

GetReconnectCount

func (s *Socket) GetReconnectCount() int

Returns the number of times the client has attempted to reconnect.

Returns: - int: Reconnection attempt counter

Example:

count := client.GetReconnectCount()
fmt.Printf("Reconnection attempts: %d\n", count)

// Use in business logic
if count > 3 {
  fmt.Println("Multiple reconnection attempts, check your connection")
}

Configuration Methods

Of

func (s *Socket) Of(path string) *Namespace

Returns a Namespace instance for the specified path. If the namespace does not exist, it creates it.

Parameters: - path (string): Namespace path (must start with /)

Returns: - *Namespace: Namespace instance

Example:

// Default namespace
client.On("global-event", handler)

// Custom namespace
chat := client.Of("/chat")
chat.On("message", func(data ...interface{}) {
  fmt.Println("Chat message:", data[0])
})

chat.Emit("join", "general-room")

// Multiple namespaces
admin := client.Of("/admin")
admin.On("alert", adminHandler)

notifications := client.Of("/notifications")
notifications.On("new", notificationHandler)

EventHandler

type EventHandler func(data ...interface{})

Function type for handling events.

AckCallback

type AckCallback func(data ...interface{})

Function type for handling acknowledgment responses.

ConnectionState

type ConnectionState int

const (
  StateDisconnected ConnectionState = iota
  StateConnecting
  StateConnected
  StateReconnecting
  StateDisconnecting
)

Possible connection states.

Thread-Safe Usage

All Socket methods are thread-safe and can be called from multiple goroutines simultaneously.

// Emit from multiple goroutines
for i := 0; i < 10; i++ {
  go func(id int) {
    client.Emit("worker", map[string]interface{}{
      "id": id,
      "data": processData(id),
    })
  }(i)
}

// Listening to events is thread-safe
client.On("result", func(data ...interface{}) {
  // This handler can be called concurrently
  go processResult(data)
})

Complete Example

package main

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

func main() {
  // Create client with options
  client := socketio.New("ws://localhost:3000", socketio.Options{
    Auth: map[string]interface{}{
      "token": "secret-token",
    },
    ReconnectAttempts: 5,
    ReconnectDelay:    time.Second,
    ReconnectDelayMax: 5 * time.Second,
    Timeout:           30 * time.Second,
    AckTimeout:        5 * time.Second,
  })
  defer client.Close()

  // Lifecycle events
  client.OnConnect(func() {
    fmt.Println("✅ Connected")

    // Emit initial event
    client.Emit("join", "main-room")
  })

  client.OnDisconnect(func(reason string) {
    fmt.Printf("❌ Disconnected: %s\n", reason)
  })

  client.OnError(func(err error) {
    fmt.Printf("⚠️  Error: %v\n", err)
  })

  // Reconnection events
  client.OnReconnectAttempt(func(attempt int) {
    fmt.Printf("🔄 Attempting to reconnect... (#%d)\n", attempt)
  })

  client.OnReconnect(func(attempt int) {
    fmt.Printf("✅ Reconnected after %d attempts\n", attempt)
  })

  // Custom events
  client.On("message", func(data ...interface{}) {
    fmt.Printf("📩 Message: %v\n", data[0])
  })

  client.On("user-joined", func(data ...interface{}) {
    username := data[0].(string)
    fmt.Printf("👤 %s joined\n", username)
  })

  // Emit with acknowledgment
  client.EmitWithAck("get-data", func(response ...interface{}) {
    if response == nil {
      fmt.Println("⏱️  Timeout waiting for response")
      return
    }
    fmt.Printf("📦 Data received: %v\n", response[0])
  }, "request-id-123")

  // Namespaces
  chat := client.Of("/chat")
  chat.On("message", func(data ...interface{}) {
    fmt.Printf("💬 Chat: %v\n", data[0])
  })

  // Check state
  if client.IsConnected() {
    fmt.Println("State: Connected")
  }

  // Keep application running
  select {}
}

See Also