socketio2

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 13 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-socketio2-client

A minimal Go client for the legacy Socket.IO v2 wire protocol — Engine.IO v3 handshake + Socket.IO v2 packet framing, i.e. whatever is on the other end of "socket.io-client": "2.x" / "socket.io": "2.x" on the Node.js side.

Only the websocket transport is implemented (no HTTP long-polling), which is sufficient for any server reachable with:

io.connect(host, { transports: ['websocket'] })

Why this exists

There is no maintained Go library for this protocol generation:

This package was written from — and verified against — the actual packages bundled with socket.io-client@2.0.4 (socket.io-parser@3.1.3, engine.io-parser@2.1.3), not just the general protocol spec.

Install

go get github.com/wenlingang/go-socketio2-client

Usage

client := socketio2.New(socketio2.Options{
    // The URL path is the Socket.IO namespace, matching how
    // socket.io-client v2's io.connect(host, opts) treats it.
    Host: "https://example.com/my-namespace",
    Query: map[string]string{
        "token": "secret",
    },
})

client.OnConnect(func() {
    // Re-join on every (re)connect — a fresh connection resets any
    // server-side room membership.
    client.Emit("join", map[string]string{"room": "lobby"})
})

client.OnEvent(func(event string, args []json.RawMessage) {
    log.Printf("received %s: %s", event, args[0])
})

client.OnDisconnect(func(err error) {
    log.Printf("disconnected: %v", err)
})

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Run blocks, reconnecting forever (matching socket.io-client v2's default
// reconnection: true, reconnectionAttempts: Infinity) until ctx is canceled.
if err := client.Run(ctx); err != nil {
    log.Fatal(err)
}
Waiting for an ack
resp, err := client.EmitWithAck(ctx, "join", map[string]string{"room": "lobby"})

What it does and doesn't do

  • Implements the Engine.IO v3 packet types (OPEN/CLOSE/PING/PONG/MESSAGE/UPGRADE/NOOP) and Socket.IO v2 packet types (CONNECT/DISCONNECT/EVENT/ACK/ERROR), encoded/decoded exactly as socket.io-parser/engine.io-parser v2-era do.
  • Drives the Engine.IO v3 heartbeat correctly: the client sends PING every pingInterval and the server answers PONG. (Engine.IO v4 inverts this — a v4-style client that waits for a server ping gets dropped as dead by a v2 server.) Any received packet also refreshes the liveness deadline.
  • Reconnects automatically with the same defaults as socket.io-client v2 (1s initial delay, 5s max, 0.5 randomization factor, unlimited attempts by default), re-running the CONNECT handshake on every attempt. Your OnConnect callback is the place to redo any subscribe/join emits.
  • Does not implement HTTP long-polling, binary/ArrayBuffer packets, or multiplexed namespaces on a single connection — one Client is one namespace, one websocket connection.

License

MIT

Documentation

Overview

Package socketio2 is a minimal client for the legacy Socket.IO v2 wire protocol (Engine.IO v3 handshake + Socket.IO v2 packet framing, the pair used by "socket.io-client": "2.x" and "socket.io": "2.x" on the server side). It only implements the websocket transport (no HTTP long-polling), which is sufficient for any server reachable with `io.connect(host, { transports: ['websocket'] })` on the Node.js side.

There is no maintained Go library for this protocol generation: googollee/go-socket.io is archived and never supported Socket.IO v2, and the handful of dedicated v2 client forks (zhouhui8915/go-socket.io-client, graarh/golang-socketio) have been unmaintained for 5+ years. This package was written from, and verified against, the actual packages bundled with socket.io-client@2.0.4 (socket.io-parser@3.1.3, engine.io-parser@2.1.3).

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("socketio2: connection closed before ack was received")

ErrClosed is returned by EmitWithAck when the connection drops before the server acknowledges the emitted event.

View Source
var ErrNotConnected = errors.New("socketio2: not connected")

ErrNotConnected is returned by Emit/EmitWithAck when called while the client has no active connection (before the first successful connect, or while reconnecting).

Functions

func DecodeEventData

func DecodeEventData(data json.RawMessage) (event string, args []json.RawMessage, err error)

DecodeEventData decodes a socket.io EVENT packet's data array (`["eventName", arg1, arg2, ...]`) into the event name and remaining args.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a reconnecting Socket.IO v2 client for a single namespace. A Client is safe for concurrent use: Emit/EmitWithAck may be called from any goroutine while Run is driving the connection.

func New

func New(opts Options) *Client

New creates a Client. It does not connect until Run is called.

func (*Client) Close

func (c *Client) Close() error

Close closes the current underlying connection, if any, which causes Run to observe a read error and proceed to its normal reconnect flow. To stop Run for good, cancel the context passed to it instead.

func (*Client) Emit

func (c *Client) Emit(event string, payload any) error

Emit sends an EVENT packet without requesting an acknowledgement.

func (*Client) EmitWithAck

func (c *Client) EmitWithAck(ctx context.Context, event string, payload any) (json.RawMessage, error)

EmitWithAck sends an EVENT packet with an ack id and blocks until the server acknowledges it, ctx is done, or the connection drops.

func (*Client) OnConnect

func (c *Client) OnConnect(handler func())

OnConnect registers a callback invoked every time the Socket.IO namespace CONNECT handshake completes, including after a reconnect. This is the place to (re-)emit subscription requests, since a fresh connection resets any server-side subscription state.

func (*Client) OnDisconnect

func (c *Client) OnDisconnect(handler func(err error))

OnDisconnect registers a callback invoked whenever the connection drops, with the error that caused it (nil if it was a clean server disconnect).

func (*Client) OnError

func (c *Client) OnError(handler func(error))

OnError registers a callback invoked for protocol-level errors that don't terminate the connection (e.g. a malformed packet, a Socket.IO ERROR packet). Fatal connection errors are instead reported via OnDisconnect.

func (*Client) OnEvent

func (c *Client) OnEvent(handler EventHandler)

OnEvent registers the callback invoked for every received EVENT packet.

All callbacks run synchronously on the connection's read goroutine, so a handler that blocks stalls delivery of every later packet. Hand slow work off to your own goroutine or buffered channel. Handlers must be registered before Run is called; they are not safe to swap while it is running.

func (*Client) Run

func (c *Client) Run(ctx context.Context) error

Run drives the connect/reconnect loop until ctx is canceled or MaxReconnectAttempts consecutive failures occur, whichever happens first. It blocks; run it in its own goroutine.

type EventHandler

type EventHandler func(event string, args []json.RawMessage)

EventHandler is called for every Socket.IO EVENT packet received on the namespace, with the event name and its remaining arguments.

type HandshakeError added in v0.1.2

type HandshakeError struct {
	StatusCode int
	Status     string
	Body       string
	Err        error
}

HandshakeError reports that the server answered the websocket upgrade with a non-101 HTTP response. gorilla's ErrBadHandshake alone can't distinguish a 403 (source IP not whitelisted) from a 400 (bad params) or a proxy that ate the Upgrade, so the status and a bounded body excerpt are kept; callers can use errors.As to tell a rejected credential (401/403), which retrying won't fix, apart from a transient network failure.

func (*HandshakeError) Error added in v0.1.2

func (e *HandshakeError) Error() string

func (*HandshakeError) Unwrap added in v0.1.2

func (e *HandshakeError) Unwrap() error

type Options

type Options struct {
	// Host is the server URL including the Socket.IO namespace as its URL
	// path, e.g. "https://example.com/my-namespace". This mirrors
	// socket.io-client v2's `io.connect(host, opts)` where the URL path is
	// treated as the namespace, not an HTTP path.
	Host string

	// Query holds extra query parameters merged into the Engine.IO
	// handshake URL (alongside the EIO/transport params this library sets
	// automatically), e.g. auth tokens the server expects on connect.
	Query map[string]string

	// Path is the Engine.IO handshake path. Defaults to "/socket.io/".
	Path string

	// DialTimeout bounds the websocket handshake. Defaults to 15s.
	DialTimeout time.Duration

	// WriteTimeout bounds a single packet write. Defaults to 10s. It stops a
	// peer that has stopped reading from blocking writes (and therefore every
	// concurrent Emit) indefinitely.
	WriteTimeout time.Duration

	// ReconnectionDelay is the initial delay before the first reconnect
	// attempt. Defaults to 1s, matching socket.io-client v2.
	ReconnectionDelay time.Duration

	// ReconnectionDelayMax caps the reconnect backoff. Defaults to 5s,
	// matching socket.io-client v2.
	ReconnectionDelayMax time.Duration

	// RandomizationFactor jitters the reconnect delay by +/- this fraction.
	// Defaults to 0.5, matching socket.io-client v2.
	RandomizationFactor float64

	// MaxReconnectAttempts caps the number of consecutive failed reconnect
	// attempts before Run gives up and returns. Zero (the default) means
	// unlimited retries, matching socket.io-client v2's default of Infinity.
	MaxReconnectAttempts int
}

Options configures a Client. Only Host is required; everything else has defaults matching socket.io-client v2's own defaults.

Directories

Path Synopsis
examples
subscriber command
Command subscriber is a minimal example of using socketio2 to join a room on a Socket.IO v2 server and log every chat message it receives.
Command subscriber is a minimal example of using socketio2 to join a room on a Socket.IO v2 server and log every chat message it receives.

Jump to

Keyboard shortcuts

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