go.socket.io

module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: MIT

README

Go Socket.IO Client

A Go implementation of the Socket.IO v5 client, compatible with Socket.IO v4 servers.

logo

License Go Report Card codecov Go Reference
Test Lint Sec CodeQL

This library implements a modular client compatible with the Socket.IO v5 protocol and Engine.IO v4 protocol. It supports WebSocket and HTTP long-polling transports, as well as the authorization mechanism introduced in Socket.IO v5.

Version 0.2.0 adds automatic reconnection, binary events and acknowledgements, independent connection timeouts, and an optional maintained WebSocket backend. See CHANGELOG.md for migration notes.

Table of Contents

Quick Start

package main

import (
 "context"
 "fmt"
 "log"
 "time"

 socketio "github.com/maldikhan/go.socket.io/socket.io/v5/client"
)

func main() {
 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
 defer cancel()

 client, err := socketio.NewClient(
  socketio.WithRawURL("http://localhost:3000"),
 )
 if err != nil {
  log.Fatalf("Error creating client: %v", err)
 }


 client.On("eventname", func(data []byte) {
  fmt.Printf("Received message: %s\n", string(data))
 })

 if err := client.Connect(ctx); err != nil {
  log.Fatalf("Error connecting to server: %v", err)
 }

 if err := client.Emit("hello", "world"); err != nil {
  log.Fatalf("Error sending message: %v", err)
 }

 <-ctx.Done()
}

More usage examples can be found in the examples project.

Features

  • Socket.IO v5 protocol support
  • Engine.IO v4 protocol support
  • WebSocket and HTTP long-polling transports
  • Authorization support
  • Configurable default namespace
  • Binary events and acknowledgements over both transports
  • Automatic reconnection with bounded exponential backoff
  • Connection timeout independent of session lifetime
  • Optional maintained WebSocket backend with compression and read limits
  • Concurrency-safe client (all public methods are goroutine-safe)
  • Modular design for easy component replacement
  • Fast JSON parsing with jsoniter (with custom parser)

Requirements

  • Go 1.26.0 or later; use the latest security patch for your Go release.

Installation

go get github.com/maldikhan/go.socket.io

Usage

Creating a client
client, err := socketio.NewClient(
 socketio.WithRawURL("http://localhost:3000"),
 socketio.WithLogger(customLogger),
)
Connecting to a server

Basic connection:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

err := client.Connect(ctx)
if err != nil {
    log.Fatal(err)
}

You can also pass one or more callback functions as additional parameters to client.Connect. These callbacks will be executed upon successful connection. This is effectively an alias for client.On("connect", func(interface{}){...}). Here's an example:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

err := client.Connect(ctx, 
    func(_ interface{}) {
        fmt.Println("Connected to the server!")
    },
    func(_ interface{}) {
        fmt.Println("This is another on-connect callback")
    },
)
if err != nil {
    log.Fatal(err)
}

You can also send the custom handshake data to the server:


accessToken := "your_access_token"

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

client.SetHandshakeData(
    map[string]interface{}{
        "access_token": accessToken,
    },
)

err := client.Connect(ctx)
if err != nil {
    log.Fatal(err)
}

This approach allows you to set up connection handlers inline with the connection call, which can be more convenient in some cases. It's particularly useful when you want to perform specific actions immediately after a successful connection, such as joining rooms or emitting initial events.

Remember that these callbacks will be called every time a connection is established, including after automatic reconnects if your client is configured to use them.

Event handling

The library allows you to handle events in two ways:

Automatically deserialize event parameters (similar to the original client)
client.On("result", func(operation string, result int) {
 // Process event ["result", "operationtype", 123]
 fmt.Printf("Operation: %s, Result: %d\n", operation, result)
})
Work with raw events
client.On("result", func(args []interface{}) {
 // Extract raw JSON data
 if arg0, ok := args[0].(json.RawMessage); ok {
  // Process raw JSON
 }
})
Catch-all handlers
// Args are parser-specific raw JSON params
client.OnAny(func(eventName string, args []interface{}) {  
 // Extract raw JSON data
 if arg0, ok := args[0].(json.RawMessage); ok {
  // Process raw JSON
 }
 // Extract raw JSON data
 if arg1, ok := args[1].(json.RawMessage); ok {
  // Process raw JSON
 }
 ...
})
Internal events

The library allows you to handle socket.io internal events:

client.On("connect", func() {
 // ... do anything on namespace connected
 // you should emit events to namespace only after NS connection
})

client.On("disconnect", func() {
 // ... do anything on disconnected
})

client.On("error", func() {
 // ... do anything on connect error
})
Emitting events

Important Note: Emitting events is only possible after a connection to the namespace has been established (i.e., after receiving the 'connect' event). When calling Emit for a namespace that hasn't established a connection yet, the Emit method will block until the 'connect' event is received from that namespace.

Simple event emission
err := client.Emit("eventName", "eventData")
if err != nil {
    log.Println("Error emitting event:", err)
}
Emitting events with acknowledgement and timeout
err = client.Emit("delay", 1000,
    emit.WithAck(func(delayResponse string) {
        fmt.Println("Ack received:", delayResponse)
    }),
    emit.WithTimeout(500*time.Millisecond, func() {
        fmt.Println("Ack timeout occurred")
    }),
)
if err != nil {
    log.Println("Error emitting event:", err)
}

To ensure proper sequencing, you can use the following pattern:

client.On("connect", func() {
    fmt.Println("Connected to namespace")
    // Now it's safe to emit events
    err := client.Emit("eventName", "eventData")
    if err != nil {
        fmt.Println("Error emitting event:", err)
    }
})

err := client.Connect(ctx)
if err != nil {
    fmt.Println("Error connecting:", err)
    return
}

This approach guarantees that you'll start emitting events only after the connection to the namespace has been established, preventing event loss and potential errors related to premature emission attempts.

Closing the connection
err := client.Close()

Advanced Configuration

Socket.IO Client Options
  • WithURL(*url.URL): Set the server URL
  • WithRawURL(string): Set the server URL as a string
  • WithEngineIOClient(EngineIOClient): Use a custom Engine.IO client
  • WithDefaultNamespace(string): Set the default namespace
  • WithLogger(Logger): Use a custom logger
  • WithTimer(Timer): Use a custom timer
  • WithParser(Parser): Use a custom parser (see jsoniter fast default event parser implementation)
  • WithConnectTimeout(time.Duration): Fail fast when the server is unreachable, without limiting the session lifetime (see Connect timeout)
Engine.IO Client Options
  • WithURL(*url.URL): Set the server URL
  • WithRawURL(string): Set the server URL as a string
  • WithLogger(Logger): Use a custom logger
  • WithTransport(Transport): Use a specific transport
  • WithSupportedTransports([]Transport): Set supported transports
  • WithParser(Parser): Use a custom parser
  • WithReconnect(bool): Enable/disable automatic reconnection (enabled by default)
  • WithReconnectAttempts(int): Set the number of reconnect attempts
  • WithReconnectWait(time.Duration): Set the base wait; retries double up to 8 times this duration
  • WithOnReconnecting(func()), WithOnReconnect(func()), WithOnReconnectFailed(func()): Register lifecycle hooks
  • WithConnectTimeout(time.Duration): Limit the duration of the connection phase only (see Connect timeout)
Connect timeout

The context passed to client.Connect(ctx) controls the lifetime of the whole session: cancelling it stops the client. This means a context.WithTimeout(ctx, 5*time.Second) would kill the client 5 seconds after connecting — and a plain context.Background() gives no way to fail fast when the server is unreachable.

Use WithConnectTimeout to bound only the connection phase (transport dial, engine.io handshake and transport upgrade). With this option set, Connect blocks until the handshake completes and returns context.DeadlineExceeded when it does not finish in time, while a successfully established session keeps running for as long as the Connect context allows:

client, err := socketio.NewClient(
    socketio.WithRawURL("http://localhost:3000"),
    socketio.WithConnectTimeout(3*time.Second),
)
if err != nil {
    log.Fatal(err)
}

// Fails after ~3s if the server is unreachable; the session itself is
// unaffected by the timeout once connected.
if err := client.Connect(context.Background()); err != nil {
    log.Fatal(err)
}

The same option is available on the engine.io client (engineio.WithConnectTimeout) when you build it yourself via WithEngineIOClient.

Alternative WebSocket backend

By default the WebSocket transport uses the native backend built on golang.org/x/net/websocket. That package is frozen and lacks permessage-deflate compression, a proper RFC 6455 close handshake and configurable read limits.

If you need those, opt in to the websocket/coder package built on github.com/coder/websocket (the actively maintained continuation of nhooyr.io/websocket). The native backend remains the default; the coder backend supports text and binary messages, configurable read limits, a custom HTTP client, and permessage-deflate compression:

import (
    engineio "github.com/maldikhan/go.socket.io/engine.io/v4/client"
    engineio_ws "github.com/maldikhan/go.socket.io/engine.io/v4/client/transport/websocket"
    ws_coder "github.com/maldikhan/go.socket.io/websocket/coder"
)

wsConn, err := ws_coder.New(
    // Optional: enable permessage-deflate compression.
    // ws_coder.WithCompression(websocket.CompressionContextTakeover),
    // Optional: cap inbound message size (default 4MB, -1 to disable).
    // ws_coder.WithReadLimit(1024 * 1024),
)
if err != nil {
    log.Fatal(err)
}

wsTransport, err := engineio_ws.NewTransport(engineio_ws.WithWebSocket(wsConn))
if err != nil {
    log.Fatal(err)
}

engineioClient, err := engineio.NewClient(
    engineio.WithRawURL("http://localhost:3000/socket.io/"),
    engineio.WithTransport(wsTransport),
)
if err != nil {
    log.Fatal(err)
}

client, err := socketio.NewClient(
    socketio.WithEngineIOClient(engineioClient),
)

The backend is only linked into your binary when you import its package. Compression is disabled by default. Use WithHTTPClient for custom TLS, proxy or cookie settings. Close performs a normal RFC 6455 close handshake; an unresponsive peer can delay the handshake by up to 10 seconds. Cancelling the session context aborts pending dials, reads and writes promptly.

Concurrency Model

This section describes the threading guarantees of the client so you don't have to read the source to use it safely.

Goroutine-safe methods

The following may be called concurrently from multiple goroutines:

  • Connect(ctx) — starts the session (call once per client lifecycle)
  • Emit(...) — safe to call from any goroutine, including from inside a handler
  • On(...) / OnAny(...) — handler registration is guarded by a mutex and may race-free be called while the client is connected
  • Close() — safe to call from any goroutine
Callback execution
  • Each registered handler is invoked in its own goroutine, so a slow or blocking handler does not stall the read loop or other handlers.
  • The OnConnect hook is likewise dispatched in a separate goroutine, so it may call Emit/Send without deadlocking the transport upgrade.
Ordering
  • Packets within a namespace are read and dispatched in receive order.
  • Because each handler runs in its own goroutine, the completion order of handlers is not guaranteed. If you need strict ordering inside a handler, serialize the work yourself (e.g. push to a channel you drain sequentially).
Backpressure
  • The Engine.IO layer buffers up to 100 inbound messages between the transport and the dispatch loop. If consumers (your handlers) cannot keep up and the buffer fills, the transport read blocks until space is available, applying backpressure to the server rather than growing memory unbounded.
Panic handling
  • A panic inside an event handler is recovered and logged (panic in event handler: ...) by the dispatcher. One misbehaving handler will not crash the client or take down other handlers.

Limitations

  • A client accepts one public Connect call. For a new manual session after failure or Close, create a new client. Automatic reconnection runs internally.

  • Reconnection establishes a new session and rejoins the configured default namespace. Events and acknowledgements from the previous session are not replayed; applications should use their own delivery IDs when replay is needed.

  • WithConnectTimeout bounds the Engine.IO handshake and transport upgrade. Wait for the Socket.IO connect event before treating a namespace as ready.

  • Call Connect once per client. Concurrent or repeated calls return ErrConnectAlreadyStarted, and calling it after Close returns ErrClientClosed. Construct a new client for another manual session; automatic reconnect attempts remain part of the original session.

  • Custom parsers must explicitly support binary reconstruction to receive binary events. Text-only custom parsers retain their serialization behavior.

  • Use the default namespace option for a custom namespace. Multiplexing several independently configured namespaces through one client is not a public API.

  • Handlers run concurrently. Applications must synchronize their shared state.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Contributors

maldikhan
maldikhan
breml
breml

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Socket.IO for the original protocol and implementation
  • jsoniter for fast JSON parsing

Directories

Path Synopsis
Package e2e contains end-to-end integration tests that run the Go client against a real Socket.IO server.
Package e2e contains end-to-end integration tests that run the Go client against a real Socket.IO server.
engine.io
v4
v4/client/mocks
Package mock_engineio_v4_client is a generated GoMock package.
Package mock_engineio_v4_client is a generated GoMock package.
v4/client/transport/polling/mocks
Package mock_engineio_v4_client_transport is a generated GoMock package.
Package mock_engineio_v4_client_transport is a generated GoMock package.
v4/client/transport/websocket/mocks
Package mock_engineio_v4_client_transport is a generated GoMock package.
Package mock_engineio_v4_client_transport is a generated GoMock package.
examples module
socket.io
v5
v5/client/mocks
Package mock_socketio_v5_client is a generated GoMock package.
Package mock_socketio_v5_client is a generated GoMock package.
v5/parser/default/mocks
Package mock_socketio_v5_parser_default is a generated GoMock package.
Package mock_socketio_v5_parser_default is a generated GoMock package.
websocket
coder
Package ws_coder provides an optional WebSocket backend with compression, message size limits and RFC 6455 close handshakes.
Package ws_coder provides an optional WebSocket backend with compression, message size limits and RFC 6455 close handshakes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL