socket

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2025 License: MIT Imports: 17 Imported by: 3

Documentation

Overview

Package socket implements a Socket.IO client in Go. It provides real-time bidirectional event-based communication between web clients and servers.

Example usage:

socket, err := socket.Connect("http://localhost:8080", nil)
if err != nil {
    log.Fatal(err)
}
socket.On("connect", func() {
    socket.Emit("hello", "world")
})

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	RESERVED_EVENTS = types.NewSet("connect", "connect_error", "disconnect", "disconnecting", "newListener", "removeListener")

	Polling      = transports.Polling
	WebSocket    = transports.WebSocket
	WebTransport = transports.WebTransport
)

Functions

This section is empty.

Types

type Engine

type Engine = engine.Socket

type EngineOptions

type EngineOptions = engine.SocketOptions

type EngineOptionsInterface

type EngineOptionsInterface = engine.SocketOptionsInterface

type ExtendedError

type ExtendedError struct {
	Message string `json:"message" msgpack:"message"`
	Data    any    `json:"data" msgpack:"data"`
}

func NewExtendedError

func NewExtendedError(message string, data any) *ExtendedError

func (*ExtendedError) Err

func (e *ExtendedError) Err() error

func (*ExtendedError) Error

func (e *ExtendedError) Error() string

type Flags

type Flags struct {
	packet.Options

	Volatile  bool           `json:"volatile" msgpack:"volatile"`
	Timeout   *time.Duration `json:"timeout,omitempty" msgpack:"timeout,omitempty"`
	FromQueue bool           `json:"fromQueue" msgpack:"fromQueue"`
}

type Handshake

type Handshake struct {
	Sid string `json:"sid" msgpack:"sid"`
	Pid string `json:"pid,omitempty" msgpack:"pid,omitempty"`
}

type Manager

type Manager struct {
	types.EventEmitter
	// contains filtered or unexported fields
}

Manager implements the Socket.IO client manager that handles connections to a Socket.IO server. It manages connection lifecycle, automatic reconnection, and socket namespaces.

Example usage:

opts := DefaultManagerOptions()
opts.SetTimeout(5 * time.Second)

manager, err := NewManager("http://localhost:8080", opts)
if err != nil {
    log.Fatal(err)
}

// Get a socket for the default namespace
socket := manager.Socket("/", nil)

func MakeManager

func MakeManager() *Manager

func NewManager

func NewManager(uri string, opts ManagerOptionsInterface) *Manager

NewManager creates a new Manager instance with the specified URI and options. It establishes and manages the connection to a Socket.IO server.

Parameters:

  • uri: The URI of the Socket.IO server (e.g., "http://localhost:8080")
  • opts: Configuration options for the manager

Returns:

  • *Manager: A new manager instance

func (*Manager) Connect

func (m *Manager) Connect(fn func(error)) *Manager

Alias for Manager.Open

func (*Manager) Construct

func (m *Manager) Construct(uri string, opts ManagerOptionsInterface)

func (*Manager) Engine

func (m *Manager) Engine() Engine

func (*Manager) Open

func (m *Manager) Open(fn func(error)) *Manager

Open initiates the connection to the server. This is called automatically when autoConnect is true (default).

Parameters:

  • fn: Optional callback that will be called when connection is established or fails

Returns:

  • *Manager: The manager instance for chaining

func (*Manager) Opts

func (m *Manager) Opts() ManagerOptionsInterface

func (*Manager) RandomizationFactor

func (m *Manager) RandomizationFactor() float64

func (*Manager) Reconnection

func (m *Manager) Reconnection() bool

func (*Manager) ReconnectionAttempts

func (m *Manager) ReconnectionAttempts() float64

func (*Manager) ReconnectionDelay

func (m *Manager) ReconnectionDelay() float64

func (*Manager) ReconnectionDelayMax

func (m *Manager) ReconnectionDelayMax() float64

func (*Manager) SetRandomizationFactor

func (m *Manager) SetRandomizationFactor(randomizationFactor float64)

Sets the maximum delay between reconnections.

func (*Manager) SetReconnection

func (m *Manager) SetReconnection(reconnection bool)

Sets the `reconnection` config.

func (*Manager) SetReconnectionAttempts

func (m *Manager) SetReconnectionAttempts(reconnectionAttempts float64)

Sets the reconnection attempts config.

func (*Manager) SetReconnectionDelay

func (m *Manager) SetReconnectionDelay(reconnectionDelay float64)

Sets the delay between reconnections.

func (*Manager) SetReconnectionDelayMax

func (m *Manager) SetReconnectionDelayMax(reconnectionDelayMax float64)

Sets the randomization factor

func (*Manager) SetTimeout

func (m *Manager) SetTimeout(timeout time.Duration)

Sets the connection timeout. `false` to disable

func (*Manager) Socket

func (m *Manager) Socket(nsp string, opts SocketOptionsInterface) *Socket

Socket creates or returns an existing Socket instance for the specified namespace.

Parameters:

  • nsp: The namespace to connect to (defaults to "/")
  • opts: Socket-specific options

Returns:

  • *Socket: A Socket instance for the namespace

func (*Manager) Timeout

func (m *Manager) Timeout() *time.Duration

type ManagerOptions

type ManagerOptions struct {
	EngineOptions
	// contains filtered or unexported fields
}

func DefaultManagerOptions

func DefaultManagerOptions() *ManagerOptions

func (*ManagerOptions) Assign

func (*ManagerOptions) AutoConnect

func (s *ManagerOptions) AutoConnect() bool

func (*ManagerOptions) ForceNew

func (s *ManagerOptions) ForceNew() bool

func (*ManagerOptions) GetRawAutoConnect

func (s *ManagerOptions) GetRawAutoConnect() *bool

func (*ManagerOptions) GetRawForceNew

func (s *ManagerOptions) GetRawForceNew() *bool

func (*ManagerOptions) GetRawMultiplex

func (s *ManagerOptions) GetRawMultiplex() *bool

func (*ManagerOptions) GetRawParser

func (s *ManagerOptions) GetRawParser() parser.Parser

func (*ManagerOptions) GetRawPath

func (s *ManagerOptions) GetRawPath() *string

func (*ManagerOptions) GetRawRandomizationFactor

func (s *ManagerOptions) GetRawRandomizationFactor() *float64

func (*ManagerOptions) GetRawReconnection

func (s *ManagerOptions) GetRawReconnection() *bool

func (*ManagerOptions) GetRawReconnectionAttempts

func (s *ManagerOptions) GetRawReconnectionAttempts() *float64

func (*ManagerOptions) GetRawReconnectionDelay

func (s *ManagerOptions) GetRawReconnectionDelay() *float64

func (*ManagerOptions) GetRawReconnectionDelayMax

func (s *ManagerOptions) GetRawReconnectionDelayMax() *float64

func (*ManagerOptions) GetRawTimeout

func (s *ManagerOptions) GetRawTimeout() *time.Duration

func (*ManagerOptions) Multiplex

func (s *ManagerOptions) Multiplex() bool

func (*ManagerOptions) Parser

func (s *ManagerOptions) Parser() parser.Parser

func (*ManagerOptions) Path

func (s *ManagerOptions) Path() string

func (*ManagerOptions) RandomizationFactor

func (s *ManagerOptions) RandomizationFactor() float64

func (*ManagerOptions) Reconnection

func (s *ManagerOptions) Reconnection() bool

func (*ManagerOptions) ReconnectionAttempts

func (s *ManagerOptions) ReconnectionAttempts() float64

func (*ManagerOptions) ReconnectionDelay

func (s *ManagerOptions) ReconnectionDelay() float64

func (*ManagerOptions) ReconnectionDelayMax

func (s *ManagerOptions) ReconnectionDelayMax() float64

func (*ManagerOptions) SetAutoConnect

func (s *ManagerOptions) SetAutoConnect(autoConnect bool)

func (*ManagerOptions) SetForceNew

func (s *ManagerOptions) SetForceNew(forceNew bool)

func (*ManagerOptions) SetMultiplex

func (s *ManagerOptions) SetMultiplex(multiplex bool)

func (*ManagerOptions) SetParser

func (s *ManagerOptions) SetParser(parser parser.Parser)

func (*ManagerOptions) SetPath

func (s *ManagerOptions) SetPath(path string)

func (*ManagerOptions) SetRandomizationFactor

func (s *ManagerOptions) SetRandomizationFactor(randomizationFactor float64)

func (*ManagerOptions) SetReconnection

func (s *ManagerOptions) SetReconnection(reconnection bool)

func (*ManagerOptions) SetReconnectionAttempts

func (s *ManagerOptions) SetReconnectionAttempts(reconnectionAttempts float64)

func (*ManagerOptions) SetReconnectionDelay

func (s *ManagerOptions) SetReconnectionDelay(reconnectionDelay float64)

func (*ManagerOptions) SetReconnectionDelayMax

func (s *ManagerOptions) SetReconnectionDelayMax(reconnectionDelayMax float64)

func (*ManagerOptions) SetTimeout

func (s *ManagerOptions) SetTimeout(timeout time.Duration)

func (*ManagerOptions) Timeout

func (s *ManagerOptions) Timeout() time.Duration

type ManagerOptionsInterface

type ManagerOptionsInterface interface {
	EngineOptionsInterface

	GetRawForceNew() *bool
	ForceNew() bool
	SetForceNew(bool)

	GetRawMultiplex() *bool
	Multiplex() bool
	SetMultiplex(bool)

	GetRawPath() *string
	Path() string
	SetPath(string)

	GetRawReconnection() *bool
	Reconnection() bool
	SetReconnection(bool)

	GetRawReconnectionAttempts() *float64
	ReconnectionAttempts() float64
	SetReconnectionAttempts(float64)

	GetRawReconnectionDelay() *float64
	ReconnectionDelay() float64
	SetReconnectionDelay(float64)

	GetRawReconnectionDelayMax() *float64
	ReconnectionDelayMax() float64
	SetReconnectionDelayMax(float64)

	GetRawRandomizationFactor() *float64
	RandomizationFactor() float64
	SetRandomizationFactor(float64)

	GetRawTimeout() *time.Duration
	Timeout() time.Duration
	SetTimeout(time.Duration)

	GetRawAutoConnect() *bool
	AutoConnect() bool
	SetAutoConnect(bool)

	GetRawParser() parser.Parser
	Parser() parser.Parser
	SetParser(parser.Parser)
}

type Options

type Options struct {
	ManagerOptions
	SocketOptions
}

func DefaultOptions

func DefaultOptions() *Options

func (*Options) Assign

func (s *Options) Assign(data OptionsInterface) OptionsInterface

type OptionsInterface

type OptionsInterface interface {
	ManagerOptionsInterface
	SocketOptionsInterface
}

type Packet

type Packet struct {
	*parser.Packet

	Options *packet.Options `json:"options,omitempty" msgpack:"options,omitempty"`
}

type QueuedPacket

type QueuedPacket struct {
	// Only used for debugging purposes. To allow deduplication on the server side, one should include a unique offset in
	// the packet, for example with crypto.randomUUID().
	//
	// @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
	Id       uint64
	Args     []any
	Flags    *Flags
	Pending  atomic.Bool
	TryCount atomic.Int64
}

type ReadyState

type ReadyState string
const (
	ReadyStateOpen    ReadyState = "open"
	ReadyStateOpening ReadyState = "opening"
	ReadyStateClosed  ReadyState = "closed"
)

type Socket

type Socket struct {
	types.EventEmitter
	// contains filtered or unexported fields
}

Socket represents a Socket.IO connection to a specific namespace. It implements an event-driven interface for real-time bidirectional communication.

Socket belongs to a specific namespace (default '/') and uses an underlying Manager for network communication. It supports event emission, acknowledgments, and automatic reconnection.

Example usage:

socket := io.Connect("http://localhost:8000", nil)

socket.On("connect", func() {
	fmt.Println("Connected!")
	// Send an event to the server
	socket.Emit("message", "Hello server!")
})

// Listen for server events
socket.On("reply", func(msg string) {
	fmt.Printf("Received: %s\n", msg)
})

// Handle disconnection
socket.On("disconnect", func(reason string) {
	fmt.Printf("Disconnected: %s\n", reason)
})
Example (Basic)

ExampleSocket_basic demonstrates the basic usage of Socket.IO client

package main

import (
	"fmt"
	"log"

	client "github.com/zishang520/engine.io-client-go/transports"
	"github.com/zishang520/engine.io/v2/transports"
	"github.com/zishang520/engine.io/v2/types"
	"github.com/zishang520/socket.io-client-go/socket"

	socket_server "github.com/zishang520/socket.io/v2/socket"
)

func main() {
	config := socket_server.DefaultServerOptions()
	config.SetTransports(types.NewSet(transports.POLLING, transports.WEBSOCKET, transports.WEBTRANSPORT))

	httpServer := types.NewWebServer(nil)
	socket_server.NewServer(httpServer, config)

	done := make(chan struct{})

	httpServer.Listen("127.0.0.1:8000", func() {
		opts := socket.DefaultOptions()
		opts.SetTransports(types.NewSet(client.Polling, client.WebSocket))
		socket, err := socket.Connect("http://127.0.0.1:8000/", opts)
		if err != nil {
			log.Fatal(err)
		}

		socket.On("connect", func(...any) {
			socket.Emit("message", "Hello server!")
			fmt.Println("Connected!")
			defer socket.Close()
			close(done)
		})

		socket.On("reply", func(args ...any) {
			if len(args) > 0 {
				if msg, ok := args[0].(string); ok {
					fmt.Printf("Received: %s\n", msg)
				}
			}
		})
	})

	<-done
	httpServer.Close(nil)

}
Output:
Connected!
Example (Disconnect)

ExampleSocket_disconnect demonstrates how to disconnect the socket

package main

import (
	"fmt"
	"log"

	client "github.com/zishang520/engine.io-client-go/transports"
	"github.com/zishang520/engine.io/v2/transports"
	"github.com/zishang520/engine.io/v2/types"
	"github.com/zishang520/socket.io-client-go/socket"

	socket_server "github.com/zishang520/socket.io/v2/socket"
)

func main() {
	config := socket_server.DefaultServerOptions()
	config.SetTransports(types.NewSet(transports.POLLING, transports.WEBSOCKET, transports.WEBTRANSPORT))

	httpServer := types.NewWebServer(nil)
	socket_server.NewServer(httpServer, config)

	done := make(chan struct{})

	httpServer.Listen("127.0.0.1:8000", func() {
		opts := socket.DefaultOptions()
		opts.SetTransports(types.NewSet(client.Polling, client.WebSocket))
		socket, err := socket.Connect("http://127.0.0.1:8000/", opts)
		if err != nil {
			log.Fatal(err)
		}

		socket.On("connect", func(...any) {
			fmt.Println("Connected!")
			socket.Disconnect()
		})

		socket.On("disconnect", func(args ...any) {
			if len(args) > 0 {
				if reason, ok := args[0].(string); ok {
					fmt.Printf("Disconnected: %s\n", reason)
					defer socket.Close()
					close(done)
				}
			}
		})

	})

	<-done
	httpServer.Close(nil)

}
Output:
Connected!
Disconnected: io client disconnect
Example (EmitWithAck)

ExampleSocket_emitWithAck demonstrates how to emit events with acknowledgement

package main

import (
	"fmt"
	"log"

	client "github.com/zishang520/engine.io-client-go/transports"
	"github.com/zishang520/engine.io/v2/transports"
	"github.com/zishang520/engine.io/v2/types"
	"github.com/zishang520/socket.io-client-go/socket"

	socket_server "github.com/zishang520/socket.io/v2/socket"
)

func main() {
	config := socket_server.DefaultServerOptions()
	config.SetTransports(types.NewSet(transports.POLLING, transports.WEBSOCKET, transports.WEBTRANSPORT))

	httpServer := types.NewWebServer(nil)
	socket_server.NewServer(httpServer, config).On("connection", func(clients ...any) {
		client := clients[0].(*socket_server.Socket)
		client.On("custom-event", func(args ...interface{}) {
			ack := args[len(args)-1].(socket_server.Ack)
			ack(args[:len(args)-1], nil)
		})
	})

	done := make(chan struct{})

	httpServer.Listen("127.0.0.1:8000", func() {
		opts := socket.DefaultOptions()
		opts.SetTransports(types.NewSet(client.Polling, client.WebSocket))
		socket, err := socket.Connect("http://127.0.0.1:8000/", opts)
		if err != nil {
			log.Fatal(err)
		}

		socket.EmitWithAck("custom-event", "received hello")(func(args []any, err error) {
			if err != nil {
				fmt.Println("Failed to receive ack")
			} else {
				fmt.Printf("Server acknowledged with: %v\n", args)
			}
			defer socket.Close()
			close(done)
		})
	})

	<-done
	httpServer.Close(nil)

}
Output:
Server acknowledged with: [received hello]
Example (OnAny)

ExampleSocket_onAny demonstrates how to listen to all events

package main

import (
	"fmt"
	"log"

	client "github.com/zishang520/engine.io-client-go/transports"
	"github.com/zishang520/engine.io/v2/transports"
	"github.com/zishang520/engine.io/v2/types"
	"github.com/zishang520/socket.io-client-go/socket"

	socket_server "github.com/zishang520/socket.io/v2/socket"
)

func main() {
	config := socket_server.DefaultServerOptions()
	config.SetTransports(types.NewSet(transports.POLLING, transports.WEBSOCKET, transports.WEBTRANSPORT))

	httpServer := types.NewWebServer(nil)
	socket_server.NewServer(httpServer, config).On("connection", func(clients ...any) {
		client := clients[0].(*socket_server.Socket)
		client.On("test-event", func(args ...interface{}) {
			client.Emit("test-event")
		})
	})

	done := make(chan struct{})

	httpServer.Listen("127.0.0.1:8000", func() {
		opts := socket.DefaultOptions()
		opts.SetTransports(types.NewSet(client.Polling, client.WebSocket))
		socket, err := socket.Connect("http://127.0.0.1:8000/", opts)
		if err != nil {
			log.Fatal(err)
		}

		socket.OnAny(func(args ...any) {
			fmt.Printf("Caught event: %v\n", args[0])
			defer socket.Close()
			close(done)
		})

		socket.Emit("test-event", "data")
	})

	<-done
	httpServer.Close(nil)

}
Output:
Caught event: test-event
Example (Timeout)

ExampleSocket_timeout demonstrates how to set timeout for acknowledgements

package main

import (
	"fmt"
	"log"
	"time"

	client "github.com/zishang520/engine.io-client-go/transports"
	"github.com/zishang520/engine.io/v2/transports"
	"github.com/zishang520/engine.io/v2/types"
	"github.com/zishang520/socket.io-client-go/socket"

	socket_server "github.com/zishang520/socket.io/v2/socket"
)

func main() {
	config := socket_server.DefaultServerOptions()
	config.SetTransports(types.NewSet(transports.POLLING, transports.WEBSOCKET, transports.WEBTRANSPORT))

	httpServer := types.NewWebServer(nil)
	socket_server.NewServer(httpServer, config)

	done := make(chan struct{})

	httpServer.Listen("127.0.0.1:8000", func() {
		opts := socket.DefaultOptions()
		opts.SetTransports(types.NewSet(client.Polling, client.WebSocket))
		socket, err := socket.Connect("http://127.0.0.1:8000/", opts)
		if err != nil {
			log.Fatal(err)
		}

		socket.Timeout(5*time.Second).EmitWithAck("delayed-event", "data")(func(args []any, err error) {
			if err != nil {
				fmt.Println("Event timed out")
			} else {
				fmt.Printf("Received response: %v\n", args)
			}
			defer socket.Close()
			close(done)
		})
	})

	<-done
	httpServer.Close(nil)

}
Output:
Event timed out
Example (Volatile)

ExampleSocket_volatile demonstrates how to send messages that may be lost

package main

import (
	"log"

	client "github.com/zishang520/engine.io-client-go/transports"
	"github.com/zishang520/engine.io/v2/transports"
	"github.com/zishang520/engine.io/v2/types"
	"github.com/zishang520/socket.io-client-go/socket"

	socket_server "github.com/zishang520/socket.io/v2/socket"
)

func main() {
	config := socket_server.DefaultServerOptions()
	config.SetTransports(types.NewSet(transports.POLLING, transports.WEBSOCKET, transports.WEBTRANSPORT))

	httpServer := types.NewWebServer(nil)
	socket_server.NewServer(httpServer, config)

	done := make(chan struct{})

	httpServer.Listen("127.0.0.1:8000", func() {
		opts := socket.DefaultOptions()
		opts.SetTransports(types.NewSet(client.Polling, client.WebSocket))
		socket, err := socket.Connect("http://127.0.0.1:8000/", opts)
		if err != nil {
			log.Fatal(err)
		}

		socket.On("connect", func(...any) {
			// The server may or may not receive this message
			socket.Volatile().Emit("hello", "world")
			defer socket.Close()
			close(done)
		})
	})

	<-done
	httpServer.Close(nil)
}

func Connect

func Connect(uri string, opts OptionsInterface) (*Socket, error)

func Io

func Io(uri string, opts OptionsInterface) (*Socket, error)

func MakeSocket

func MakeSocket() *Socket

func NewSocket

func NewSocket(io *Manager, nsp string, opts SocketOptionsInterface) *Socket

func (*Socket) Active

func (s *Socket) Active() bool

Active checks whether the Socket will try to reconnect when its Manager connects or reconnects.

Example:

socket := io.NewClient("", nil)
fmt.Println(socket.Active()) // true

socket.On("disconnect", func(reason ...any) {
  if reason[0].(string) == "io server disconnect" {
    // the disconnection was initiated by the server, you need to manually reconnect
    fmt.Println(socket.Active()) // false
  }
  // else the socket will automatically try to reconnect
  fmt.Println(socket.Active()) // true
})

func (*Socket) Auth

func (s *Socket) Auth() map[string]any

func (*Socket) Close

func (s *Socket) Close() *Socket

Alias for Socket.Disconnect.

func (*Socket) Compress

func (s *Socket) Compress(compress bool) *Socket

Compress sets the compress flag.

Example:

socket := io.NewClient("", nil)
socket.Compress(false).Emit("hello")

compress: If `true`, compresses the sending data.

func (*Socket) Connect

func (s *Socket) Connect() *Socket

Connect "opens" the socket.

Example:

socket := io.NewClient("", nil)
socket.SetAutoConnect(false)
socket.Connect()

func (*Socket) Connected

func (s *Socket) Connected() bool

func (*Socket) Construct

func (s *Socket) Construct(io *Manager, nsp string, opts SocketOptionsInterface)

Construct initializes the Socket instance.

io: The Manager instance. nsp: The namespace. opts: The socket options.

func (*Socket) Disconnect

func (s *Socket) Disconnect() *Socket

Disconnect disconnects the socket manually. In that case, the socket will not try to reconnect.

If this is the last active Socket instance of the Manager, the low-level connection will be closed.

Example:

socket := io.NewClient("", nil)
socket.On("disconnect", func(reason ...any) {
  fmt.Println(reason[0]) // prints "io client disconnect"
})

socket.Disconnect()

func (*Socket) Disconnected

func (s *Socket) Disconnected() bool

Disconnected checks whether the socket is currently disconnected.

Example:

socket := io.NewClient("", nil)
socket.On("connect", func(...any) {
  fmt.Println(socket.Disconnected()) // false
})

socket.On("disconnect", func(...any) {
  fmt.Println(socket.Disconnected()) // true
})

func (*Socket) Emit

func (s *Socket) Emit(ev string, args ...any) error

Emit overrides the default emit behavior. If the event is in `events`, it's emitted normally.

Example:

socket := io.NewClient("", nil)
socket.Emit("hello", "world")

// all serializable datastructures are supported (no need to call JSON.stringify)
socket.Emit("hello", 1, "2", map[int][]string{3: {"4"}, 5: {"6"}})

// with an acknowledgement from the server

socket.Emit("hello", "world", func(val []any, err error) {
  // ...
})

func (*Socket) EmitWithAck

func (s *Socket) EmitWithAck(ev string, args ...any) func(socket.Ack)

EmitWithAck emits an event and waits for an acknowledgement.

Example:

// without timeout
socket.EmitWithAck("hello", "world")(func([]any, error){

})

// with a specific timeout
socket.Timeout(1000 * time.Millisecond).EmitWithAck("hello", "world")(func([]any, error){

})

func (*Socket) Id

func (s *Socket) Id() string

func (*Socket) Io

func (s *Socket) Io() *Manager

func (*Socket) ListenersAny

func (s *Socket) ListenersAny() []events.Listener

ListenersAny returns an array of listeners that are listening for any event that is specified. This array can be manipulated, e.g. to remove listeners.

func (*Socket) ListenersAnyOutgoing

func (s *Socket) ListenersAnyOutgoing() []events.Listener

ListenersAnyOutgoing returns an array of listeners that are listening for any event that is specified. This array can be manipulated, e.g. to remove listeners.

func (*Socket) OffAny

func (s *Socket) OffAny(listener events.Listener) *Socket

OffAny removes the listener that will be fired when any event is emitted.

Example:

catchAllListener := func(...any) {
  fmt.Println("got event")
}

socket := io.NewClient("", nil)
socket.OnAny(catchAllListener)

// remove a specific listener
socket.OffAny(catchAllListener)

// or remove all listeners
socket.OffAny()

func (*Socket) OffAnyOutgoing

func (s *Socket) OffAnyOutgoing(listener events.Listener) *Socket

OffAnyOutgoing removes the listener that will be fired when any event is emitted.

Example:

catchAllListener := func(...any) {
  fmt.Println("sent event")
}

socket := io.NewClient("", nil)
socket.OnAnyOutgoing(catchAllListener)

// remove a specific listener
socket.OffAnyOutgoing(catchAllListener)

// or remove all listeners
socket.OffAnyOutgoing()

func (*Socket) OnAny

func (s *Socket) OnAny(listener events.Listener) *Socket

OnAny adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the callback.

Example:

socket := io.NewClient("", nil)
socket.OnAny(func(...any) {
  fmt.Println("got event")
})

func (*Socket) OnAnyOutgoing

func (s *Socket) OnAnyOutgoing(listener events.Listener) *Socket

OnAnyOutgoing adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the callback.

Note: acknowledgements sent to the server are not included.

Example:

socket := io.NewClient("", nil)
socket.OnAnyOutgoing(func(...any) {
  fmt.Println("sent event")
})

func (*Socket) Open

func (s *Socket) Open() *Socket

Open is an alias for Connect.

func (*Socket) PrependAny

func (s *Socket) PrependAny(listener events.Listener) *Socket

PrependAny adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the callback. The listener is added to the beginning of the listeners array.

Example:

socket := io.NewClient("", nil)
socket.PrependAny(func(...any) {
  fmt.Println("got event")
})

func (*Socket) PrependAnyOutgoing

func (s *Socket) PrependAnyOutgoing(listener events.Listener) *Socket

PrependAnyOutgoing adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the callback. The listener is added to the beginning of the listeners array.

Note: acknowledgements sent to the server are not included.

Example:

socket := io.NewClient("", nil)
socket.PrependAnyOutgoing(func(...any) {
  fmt.Println("sent event")
})

func (*Socket) ReceiveBuffer

func (s *Socket) ReceiveBuffer() *types.Slice[[]any]

func (*Socket) Recovered

func (s *Socket) Recovered() bool

func (*Socket) Send

func (s *Socket) Send(args ...any) *Socket

Send sends a `message` event.

This method mimics the WebSocket.send() method.

Example:

socket := io.NewClient("", nil)
socket.Send("hello")

// this is equivalent to
socket.Emit("message", "hello")

func (*Socket) SendBuffer

func (s *Socket) SendBuffer() *types.Slice[*Packet]

func (*Socket) Timeout

func (s *Socket) Timeout(timeout time.Duration) *Socket

Timeout sets a modifier for a subsequent event emission that the callback will be called with an error when the given number of milliseconds have elapsed without an acknowledgement from the server:

Example:

socket := io.NewClient("", nil)
socket.Timeout(5000 * time.Millisecond).Emit("my-event", func([]any, err) {
  if err != nil {
    // the server did not acknowledge the event in the given delay
  }
})

func (*Socket) Volatile

func (s *Socket) Volatile() *Socket

Volatile sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not ready to send messages.

Example:

socket := io.NewClient("", nil)
socket.Volatile().Emit("hello") // the server may or may not receive it

type SocketOptions

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

SocketOptions defines configuration options for individual Socket.IO sockets. These options control the behavior of a specific namespace connection.

Example usage:

opts := DefaultSocketOptions()
opts.SetAuth(map[string]any{
    "token": "abc123",
})
opts.SetAckTimeout(5 * time.Second)

socket := io.Socket("/admin", opts)

func DefaultSocketOptions

func DefaultSocketOptions() *SocketOptions

DefaultSocketOptions creates a new SocketOptions instance with default values. Use this function to create a base configuration that can be customized.

func (*SocketOptions) AckTimeout

func (s *SocketOptions) AckTimeout() time.Duration

AckTimeout returns the current acknowledgement timeout duration.

func (*SocketOptions) Assign

Assign copies all options from another SocketOptionsInterface instance.

Parameters:

  • opts: The source options to copy from

Returns:

  • SocketOptionsInterface: The updated options instance

func (*SocketOptions) Auth

func (s *SocketOptions) Auth() map[string]any

Auth returns the authentication data for the socket connection.

func (*SocketOptions) GetRawAckTimeout

func (s *SocketOptions) GetRawAckTimeout() *time.Duration

GetRawAckTimeout returns the raw acknowledgement timeout setting.

func (*SocketOptions) GetRawAuth

func (s *SocketOptions) GetRawAuth() map[string]any

GetRawAuth returns the raw authentication data configuration.

func (*SocketOptions) GetRawRetries

func (s *SocketOptions) GetRawRetries() *float64

GetRawRetries returns the raw retry count

func (*SocketOptions) Retries

func (s *SocketOptions) Retries() float64

Retries returns the maximum number of retries for packet delivery

func (*SocketOptions) SetAckTimeout

func (s *SocketOptions) SetAckTimeout(ackTimeout time.Duration)

SetAckTimeout sets how long to wait for an acknowledgement before timing out.

Parameters:

  • d: The timeout duration

func (*SocketOptions) SetAuth

func (s *SocketOptions) SetAuth(auth map[string]any)

SetAuth configures the authentication data to be sent with the connection.

Parameters:

  • auth: A map containing authentication credentials or tokens

func (*SocketOptions) SetRetries

func (s *SocketOptions) SetRetries(retries float64)

SetRetries sets the maximum number of retries for packet delivery

Parameters:

  • retries: The maximum number of retries

type SocketOptionsInterface

type SocketOptionsInterface interface {
	// GetRawAuth returns the raw authentication data
	GetRawAuth() map[string]any

	// Auth returns the authentication data that will be sent with the connection.
	// This is useful for passing authentication tokens or other credentials.
	Auth() map[string]any

	// SetAuth sets the authentication data for the socket connection
	SetAuth(map[string]any)

	// GetRawRetries returns the raw retry count
	GetRawRetries() *float64

	// Retries returns the maximum number of retries for packet delivery
	Retries() float64

	// SetRetries sets the maximum number of retries for packet delivery
	SetRetries(float64)

	// GetRawAckTimeout returns the raw acknowledgement timeout value
	GetRawAckTimeout() *time.Duration

	// AckTimeout returns the timeout duration for acknowledgements
	AckTimeout() time.Duration

	// SetAckTimeout sets the timeout duration for waiting for acknowledgements
	SetAckTimeout(time.Duration)
}

SocketOptionsInterface defines the interface for accessing and modifying Socket options.

Example usage:

opts := DefaultSocketOptions()
opts.SetAuth(map[string]any{
    "token": "abc123",
})
opts.SetAckTimeout(5 * time.Second)

socket := io.Socket("/admin", opts)

Jump to

Keyboard shortcuts

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