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 ¶
- Variables
- func DecodeEventData(data json.RawMessage) (event string, args []json.RawMessage, err error)
- type Client
- func (c *Client) Close() error
- func (c *Client) Emit(event string, payload any) error
- func (c *Client) EmitWithAck(ctx context.Context, event string, payload any) (json.RawMessage, error)
- func (c *Client) OnConnect(handler func())
- func (c *Client) OnDisconnect(handler func(err error))
- func (c *Client) OnError(handler func(error))
- func (c *Client) OnEvent(handler EventHandler)
- func (c *Client) Run(ctx context.Context) error
- type EventHandler
- type HandshakeError
- type Options
Constants ¶
This section is empty.
Variables ¶
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.
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 (*Client) Close ¶
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) 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 ¶
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 ¶
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.
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
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. |