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 ¶
- Variables
- type Engine
- type EngineOptions
- type EngineOptionsInterface
- type ExtendedError
- type Flags
- type Handshake
- type Manager
- func (m *Manager) Connect(fn func(error)) *Manager
- func (m *Manager) Construct(uri string, opts ManagerOptionsInterface)
- func (m *Manager) Engine() Engine
- func (m *Manager) Open(fn func(error)) *Manager
- func (m *Manager) Opts() ManagerOptionsInterface
- func (m *Manager) RandomizationFactor() float64
- func (m *Manager) Reconnection() bool
- func (m *Manager) ReconnectionAttempts() float64
- func (m *Manager) ReconnectionDelay() float64
- func (m *Manager) ReconnectionDelayMax() float64
- func (m *Manager) SetRandomizationFactor(randomizationFactor float64)
- func (m *Manager) SetReconnection(reconnection bool)
- func (m *Manager) SetReconnectionAttempts(reconnectionAttempts float64)
- func (m *Manager) SetReconnectionDelay(reconnectionDelay float64)
- func (m *Manager) SetReconnectionDelayMax(reconnectionDelayMax float64)
- func (m *Manager) SetTimeout(timeout time.Duration)
- func (m *Manager) Socket(nsp string, opts SocketOptionsInterface) *Socket
- func (m *Manager) Timeout() *time.Duration
- type ManagerOptions
- func (s *ManagerOptions) Assign(data ManagerOptionsInterface) ManagerOptionsInterface
- func (s *ManagerOptions) AutoConnect() bool
- func (s *ManagerOptions) ForceNew() bool
- func (s *ManagerOptions) GetRawAutoConnect() *bool
- func (s *ManagerOptions) GetRawForceNew() *bool
- func (s *ManagerOptions) GetRawMultiplex() *bool
- func (s *ManagerOptions) GetRawParser() parser.Parser
- func (s *ManagerOptions) GetRawPath() *string
- func (s *ManagerOptions) GetRawRandomizationFactor() *float64
- func (s *ManagerOptions) GetRawReconnection() *bool
- func (s *ManagerOptions) GetRawReconnectionAttempts() *float64
- func (s *ManagerOptions) GetRawReconnectionDelay() *float64
- func (s *ManagerOptions) GetRawReconnectionDelayMax() *float64
- func (s *ManagerOptions) GetRawTimeout() *time.Duration
- func (s *ManagerOptions) Multiplex() bool
- func (s *ManagerOptions) Parser() parser.Parser
- func (s *ManagerOptions) Path() string
- func (s *ManagerOptions) RandomizationFactor() float64
- func (s *ManagerOptions) Reconnection() bool
- func (s *ManagerOptions) ReconnectionAttempts() float64
- func (s *ManagerOptions) ReconnectionDelay() float64
- func (s *ManagerOptions) ReconnectionDelayMax() float64
- func (s *ManagerOptions) SetAutoConnect(autoConnect bool)
- func (s *ManagerOptions) SetForceNew(forceNew bool)
- func (s *ManagerOptions) SetMultiplex(multiplex bool)
- func (s *ManagerOptions) SetParser(parser parser.Parser)
- func (s *ManagerOptions) SetPath(path string)
- func (s *ManagerOptions) SetRandomizationFactor(randomizationFactor float64)
- func (s *ManagerOptions) SetReconnection(reconnection bool)
- func (s *ManagerOptions) SetReconnectionAttempts(reconnectionAttempts float64)
- func (s *ManagerOptions) SetReconnectionDelay(reconnectionDelay float64)
- func (s *ManagerOptions) SetReconnectionDelayMax(reconnectionDelayMax float64)
- func (s *ManagerOptions) SetTimeout(timeout time.Duration)
- func (s *ManagerOptions) Timeout() time.Duration
- type ManagerOptionsInterface
- type Options
- type OptionsInterface
- type Packet
- type QueuedPacket
- type ReadyState
- type Socket
- func (s *Socket) Active() bool
- func (s *Socket) Auth() map[string]any
- func (s *Socket) Close() *Socket
- func (s *Socket) Compress(compress bool) *Socket
- func (s *Socket) Connect() *Socket
- func (s *Socket) Connected() bool
- func (s *Socket) Construct(io *Manager, nsp string, opts SocketOptionsInterface)
- func (s *Socket) Disconnect() *Socket
- func (s *Socket) Disconnected() bool
- func (s *Socket) Emit(ev string, args ...any) error
- func (s *Socket) EmitWithAck(ev string, args ...any) func(socket.Ack)
- func (s *Socket) Id() string
- func (s *Socket) Io() *Manager
- func (s *Socket) ListenersAny() []events.Listener
- func (s *Socket) ListenersAnyOutgoing() []events.Listener
- func (s *Socket) OffAny(listener events.Listener) *Socket
- func (s *Socket) OffAnyOutgoing(listener events.Listener) *Socket
- func (s *Socket) OnAny(listener events.Listener) *Socket
- func (s *Socket) OnAnyOutgoing(listener events.Listener) *Socket
- func (s *Socket) Open() *Socket
- func (s *Socket) PrependAny(listener events.Listener) *Socket
- func (s *Socket) PrependAnyOutgoing(listener events.Listener) *Socket
- func (s *Socket) ReceiveBuffer() *types.Slice[[]any]
- func (s *Socket) Recovered() bool
- func (s *Socket) Send(args ...any) *Socket
- func (s *Socket) SendBuffer() *types.Slice[*Packet]
- func (s *Socket) Timeout(timeout time.Duration) *Socket
- func (s *Socket) Volatile() *Socket
- type SocketOptions
- func (s *SocketOptions) AckTimeout() time.Duration
- func (s *SocketOptions) Assign(data SocketOptionsInterface) SocketOptionsInterface
- func (s *SocketOptions) Auth() map[string]any
- func (s *SocketOptions) GetRawAckTimeout() *time.Duration
- func (s *SocketOptions) GetRawAuth() map[string]any
- func (s *SocketOptions) GetRawRetries() *float64
- func (s *SocketOptions) Retries() float64
- func (s *SocketOptions) SetAckTimeout(ackTimeout time.Duration)
- func (s *SocketOptions) SetAuth(auth map[string]any)
- func (s *SocketOptions) SetRetries(retries float64)
- type SocketOptionsInterface
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 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 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) Construct ¶
func (m *Manager) Construct(uri string, opts ManagerOptionsInterface)
func (*Manager) Open ¶
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 (*Manager) Reconnection ¶
func (*Manager) ReconnectionAttempts ¶
func (*Manager) ReconnectionDelay ¶
func (*Manager) ReconnectionDelayMax ¶
func (*Manager) SetRandomizationFactor ¶
Sets the maximum delay between reconnections.
func (*Manager) SetReconnection ¶
Sets the `reconnection` config.
func (*Manager) SetReconnectionAttempts ¶
Sets the reconnection attempts config.
func (*Manager) SetReconnectionDelay ¶
Sets the delay between reconnections.
func (*Manager) SetReconnectionDelayMax ¶
Sets the randomization factor
func (*Manager) SetTimeout ¶
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
type ManagerOptions ¶
type ManagerOptions struct {
EngineOptions
// contains filtered or unexported fields
}
func DefaultManagerOptions ¶
func DefaultManagerOptions() *ManagerOptions
func (*ManagerOptions) Assign ¶
func (s *ManagerOptions) Assign(data ManagerOptionsInterface) ManagerOptionsInterface
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 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)
}
Output:
func MakeSocket ¶
func MakeSocket() *Socket
func (*Socket) Active ¶
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) Compress ¶
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 ¶
Connect "opens" the socket.
Example:
socket := io.NewClient("", nil)
socket.SetAutoConnect(false)
socket.Connect()
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 ¶
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 ¶
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 ¶
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 ¶
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) ListenersAny ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) PrependAny ¶
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 ¶
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) Send ¶
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) Timeout ¶
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
}
})
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 ¶
func (s *SocketOptions) Assign(data SocketOptionsInterface) SocketOptionsInterface
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)