Socket API Reference¶
The Socket type is the main client that handles the connection to the Socket.IO server.
Table of Contents¶
Creation¶
New¶
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¶
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¶
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¶
Registers a handler that executes when the connection is successfully established.
Parameters: - handler (func()): Function to execute on connection
Example:
OnDisconnect¶
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¶
Registers a handler that executes when an error occurs.
Parameters: - handler (func(err error)): Function that receives the error
Example:
OnReconnectAttempt¶
Registers a handler that executes before each reconnection attempt.
Parameters: - handler (func(attempt int)): Function that receives the attempt number
Example:
OnReconnect¶
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:
OnReconnectError¶
Registers a handler that executes when a reconnection attempt fails.
Parameters: - handler (func(err error)): Function that receives the error
Example:
OnReconnectFailed¶
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¶
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¶
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¶
Returns whether the client is currently connected to the server.
Returns: - bool: true if connected, false otherwise
Example:
GetState¶
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¶
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¶
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)
Related Types¶
EventHandler¶
Function type for handling events.
AckCallback¶
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 {}
}