engine

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: 31 Imported by: 1

Documentation

Overview

Package engine implements the Engine.IO client transport layer.

Package engine implements a client-side Engine.IO transport layer. It provides real-time bidirectional communication between clients and servers using various transport mechanisms including WebSocket, HTTP long-polling, and WebTransport.

The package supports automatic transport upgrade, binary data transmission, and reconnection handling. It is designed to be the foundation for higher-level protocols like Socket.IO.

Index

Constants

View Source
const (
	// EventBeforeUnload is emitted when the application is about to unload/exit.
	// This allows for graceful cleanup of connections.
	EventBeforeUnload types.EventName = "beforeunload"

	// EventOffline is emitted when the network connection is lost.
	// This can be used to handle disconnection scenarios.
	EventOffline types.EventName = "offline"

	// EventOnline is emitted when the network connection is restored.
	// This can be used to handle reconnection scenarios.
	EventOnline types.EventName = "online"
)

Event names for system-level events that can be emitted by the Engine.IO client.

View Source
const BASE64_OVERHEAD float64 = 1.33

BASE64_OVERHEAD represents the size overhead when encoding binary data as base64. Base64 encoding increases the size of binary data by approximately 33%. See: https://en.wikipedia.org/wiki/Base64

View Source
const Protocol = parser.Protocol

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	// Message is a human-readable description of the error.
	// It provides a clear explanation of what went wrong.
	Message string

	// Description contains the underlying error that caused this transport error.
	// This can be nil if there is no underlying error.
	Description error

	// Type identifies the category of the error (e.g., "TransportError").
	// This helps in error classification and handling.
	Type string

	// Context contains additional context information about the error.
	// This can include request/response data, timing information, etc.
	Context context.Context
	// contains filtered or unexported fields
}

Error represents a custom error type for Engine.IO transport errors. It provides detailed information about transport-related errors, including the error message, underlying cause, error type, and additional context.

The Error type implements both the standard error interface and the errors.Unwrap interface, allowing it to work seamlessly with Go's error handling mechanisms.

func NewTransportError

func NewTransportError(reason string, description error, context context.Context) *Error

NewTransportError creates a new transport error with the specified details. This is a convenience function for creating transport-specific errors with appropriate context and type information.

Parameters:

  • reason: A human-readable description of the error
  • description: The underlying error that caused this transport error (can be nil)
  • context: Additional context information about the error (can be nil)

Returns:

  • *Error: A new Error instance configured as a transport error

Example:

err := NewTransportError(
    "connection timeout",
    errors.New("read deadline exceeded"),
    ctx,
)

func (*Error) Err

func (e *Error) Err() error

Err returns the error interface implementation. This method allows the Error type to be used as a standard error.

Returns:

  • error: The error interface implementation

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface. It returns a human-readable error message describing what went wrong.

Returns:

  • string: The error message

func (*Error) Unwrap

func (e *Error) Unwrap() []error

Unwrap returns the slice of underlying errors. This implements the errors.Unwrap interface for error chain inspection. It allows the Error type to work with Go's error wrapping mechanisms like errors.Is and errors.As.

Returns:

  • []error: The slice of underlying errors

type HandshakeData

type HandshakeData struct {
	// Sid is the unique session identifier assigned by the server.
	// This ID is used to maintain the connection state and identify the client.
	Sid string `json:"sid,omitempty" msgpack:"sid,omitempty"`

	// Upgrades contains a list of transport types that the server supports
	// for upgrading the current connection. This is used in the transport
	// upgrade process to determine available upgrade options.
	Upgrades []string `json:"upgrades,omitempty" msgpack:"upgrades,omitempty"`

	// PingInterval specifies the interval (in milliseconds) between ping messages
	// sent by the client to keep the connection alive.
	PingInterval int64 `json:"pingInterval,omitempty" msgpack:"pingInterval,omitempty"`

	// PingTimeout specifies the maximum time (in milliseconds) to wait for a pong
	// response before considering the connection dead.
	PingTimeout int64 `json:"pingTimeout,omitempty" msgpack:"pingTimeout,omitempty"`

	// MaxPayload specifies the maximum size (in bytes) of a single packet that
	// can be transmitted over the connection.
	MaxPayload int64 `json:"maxPayload,omitempty" msgpack:"maxPayload,omitempty"`
}

HandshakeData represents the data exchanged during the initial handshake between the client and server. This data contains essential connection parameters and configuration options.

type Log

type Log struct {
	*log.Log
}

Log implements formatted logging for Engine.IO components.

func NewLog

func NewLog(prefix string) *Log

NewLog returns a logger that prefixes messages with prefix.

Example:

log := NewLog("websocket")
log.Debugf("state: %s", state) // Output: [websocket] state: connected

func (*Log) Debugf

func (l *Log) Debugf(message string, args ...any)

Debugf logs a debug message using format and args.

Example:

log.Debugf("bytes: %d", n)

func (*Log) Errorf

func (l *Log) Errorf(message string, args ...any)

Errorf logs an error message using format and args.

Example:

log.Errorf("failed: %v", err)

func (*Log) Warnf

func (l *Log) Warnf(message string, args ...any)

Warnf logs a warning message using format and args.

Example:

log.Warnf("using: %s", transport)

type Polling

type Polling interface {
	Transport
}

Polling represents the HTTP long-polling transport type. This transport uses regular HTTP requests to simulate real-time communication by maintaining a persistent connection through repeated requests.

Features:

  • Maximum compatibility across browsers and networks
  • Works through most proxies and firewalls
  • Fallback transport when WebSocket is not available
  • Automatic reconnection handling

func MakePolling

func MakePolling() Polling

MakePolling creates a new polling transport instance with default settings. This is the factory function for creating a new polling transport.

Returns:

  • Polling: A new polling transport instance initialized with default settings

func NewPolling

func NewPolling(socket Socket, opts SocketOptionsInterface) Polling

NewPolling creates a new polling transport instance with the specified socket and options.

Parameters:

  • socket: The parent socket instance
  • opts: The socket options configuration

Returns:

  • Polling: A new polling transport instance configured with the specified options

type PollingBuilder

type PollingBuilder struct{}

PollingBuilder implements the transport builder pattern for HTTP long-polling connections. It provides a factory method for creating new Polling transport instances.

func (*PollingBuilder) Name

func (*PollingBuilder) Name() string

Name returns the identifier for the Polling transport type.

Returns:

  • string: The transport name ("polling")

func (*PollingBuilder) New

New creates a new Polling transport instance.

Parameters:

  • socket: The parent socket instance
  • opts: The socket options configuration

Returns:

  • Transport: A new Polling transport instance

type Socket

type Socket interface {
	SocketWithUpgrade
}

Socket provides the recommended high-level interface for Engine.IO client connections. This interface extends SocketWithUpgrade to provide the most feature-complete implementation with automatic transport upgrades and optimal performance.

Key features:

  • Automatic transport upgrade mechanism
  • Multiple transport support (WebSocket, WebTransport, Polling)
  • Event-based communication
  • Support for binary data
  • Automatic reconnection
  • Comprehensive error handling
  • Binary data support
  • Cross-platform compatibility

Example usage:

socket := NewSocket("http://localhost:8080", DefaultSocketOptions())

socket.On("open", func() {
    socket.Send("hello")
})

socket.On("message", func(data any) {
    fmt.Printf("Received: %v\n", data)
})

socket.On("error", func(err any) {
    fmt.Printf("Error: %v\n", err)
})

Events:

  • "open": Emitted when the connection is established
  • "close": Emitted when the connection is closed
  • "error": Emitted when an error occurs
  • "message": Emitted when data is received
  • "upgrade": Emitted when transport upgrade is successful
  • "upgradeError": Emitted when transport upgrade fails
  • "ping": Emitted when a ping packet is received
  • "pong": Emitted when a pong packet is sent

See: SocketWithoutUpgrade for a simpler implementation without transport upgrade See: SocketWithUpgrade for the base implementation with upgrade support

func MakeSocket

func MakeSocket() Socket

MakeSocket creates a new Socket instance with default settings. This is the factory function for creating a new socket.

Returns:

  • Socket: A new Socket instance initialized with default settings.

func NewSocket

func NewSocket(uri string, opts SocketOptionsInterface) Socket

NewSocket creates a new Socket instance with the specified URI and options.

Parameters:

  • uri: The URI to connect to (e.g., "http://localhost:8080")
  • opts: Socket configuration options. If nil, default options will be used

Returns:

  • Socket: A new Socket instance configured with the specified options

type SocketOptions

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

SocketOptions implements the SocketOptionsInterface and provides the default configuration for Socket connections. It contains all the necessary parameters to establish and maintain a connection to an Engine.IO server.

func DefaultSocketOptions

func DefaultSocketOptions() *SocketOptions

func (*SocketOptions) AddTrailingSlash

func (s *SocketOptions) AddTrailingSlash() bool

func (*SocketOptions) Agent

func (s *SocketOptions) Agent() string

func (*SocketOptions) Assign

func (*SocketOptions) AutoUnref

func (s *SocketOptions) AutoUnref() bool

func (*SocketOptions) CloseOnBeforeunload

func (s *SocketOptions) CloseOnBeforeunload() bool

func (*SocketOptions) ExtraHeaders

func (s *SocketOptions) ExtraHeaders() http.Header

func (*SocketOptions) ForceBase64

func (s *SocketOptions) ForceBase64() bool

func (*SocketOptions) GetRawAddTrailingSlash

func (s *SocketOptions) GetRawAddTrailingSlash() *bool

func (*SocketOptions) GetRawAgent

func (s *SocketOptions) GetRawAgent() *string

func (*SocketOptions) GetRawAutoUnref

func (s *SocketOptions) GetRawAutoUnref() *bool

func (*SocketOptions) GetRawCloseOnBeforeunload

func (s *SocketOptions) GetRawCloseOnBeforeunload() *bool

func (*SocketOptions) GetRawExtraHeaders

func (s *SocketOptions) GetRawExtraHeaders() http.Header

func (*SocketOptions) GetRawForceBase64

func (s *SocketOptions) GetRawForceBase64() *bool

func (*SocketOptions) GetRawHost

func (s *SocketOptions) GetRawHost() *string

func (*SocketOptions) GetRawHostname

func (s *SocketOptions) GetRawHostname() *string

func (*SocketOptions) GetRawPath

func (s *SocketOptions) GetRawPath() *string

func (*SocketOptions) GetRawPerMessageDeflate

func (s *SocketOptions) GetRawPerMessageDeflate() *types.PerMessageDeflate

func (*SocketOptions) GetRawPort

func (s *SocketOptions) GetRawPort() *string

func (*SocketOptions) GetRawProtocols

func (s *SocketOptions) GetRawProtocols() []string

func (*SocketOptions) GetRawQUICConfig

func (s *SocketOptions) GetRawQUICConfig() *quic.Config

func (*SocketOptions) GetRawQuery

func (s *SocketOptions) GetRawQuery() url.Values

func (*SocketOptions) GetRawRememberUpgrade

func (s *SocketOptions) GetRawRememberUpgrade() *bool

func (*SocketOptions) GetRawRequestTimeout

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

func (*SocketOptions) GetRawSecure

func (s *SocketOptions) GetRawSecure() *bool

func (*SocketOptions) GetRawTLSClientConfig

func (s *SocketOptions) GetRawTLSClientConfig() *tls.Config

func (*SocketOptions) GetRawTimestampParam

func (s *SocketOptions) GetRawTimestampParam() *string

func (*SocketOptions) GetRawTimestampRequests

func (s *SocketOptions) GetRawTimestampRequests() *bool

func (*SocketOptions) GetRawTransportOptions

func (s *SocketOptions) GetRawTransportOptions() map[string]SocketOptionsInterface

func (*SocketOptions) GetRawTransports

func (s *SocketOptions) GetRawTransports() *types.Set[TransportCtor]

func (*SocketOptions) GetRawTryAllTransports

func (s *SocketOptions) GetRawTryAllTransports() *bool

func (*SocketOptions) GetRawUpgrade

func (s *SocketOptions) GetRawUpgrade() *bool

func (*SocketOptions) GetRawUseNativeTimers

func (s *SocketOptions) GetRawUseNativeTimers() *bool

func (*SocketOptions) GetRawWithCredentials

func (s *SocketOptions) GetRawWithCredentials() *bool

func (*SocketOptions) Host

func (s *SocketOptions) Host() string

func (*SocketOptions) Hostname

func (s *SocketOptions) Hostname() string

func (*SocketOptions) Path

func (s *SocketOptions) Path() string

func (*SocketOptions) PerMessageDeflate

func (s *SocketOptions) PerMessageDeflate() *types.PerMessageDeflate

func (*SocketOptions) Port

func (s *SocketOptions) Port() string

func (*SocketOptions) Protocols

func (s *SocketOptions) Protocols() []string

func (*SocketOptions) QUICConfig

func (s *SocketOptions) QUICConfig() *quic.Config

func (*SocketOptions) Query

func (s *SocketOptions) Query() url.Values

func (*SocketOptions) RememberUpgrade

func (s *SocketOptions) RememberUpgrade() bool

func (*SocketOptions) RequestTimeout

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

func (*SocketOptions) Secure

func (s *SocketOptions) Secure() bool

func (*SocketOptions) SetAddTrailingSlash

func (s *SocketOptions) SetAddTrailingSlash(addTrailingSlash bool)

func (*SocketOptions) SetAgent

func (s *SocketOptions) SetAgent(agent string)

func (*SocketOptions) SetAutoUnref

func (s *SocketOptions) SetAutoUnref(autoUnref bool)

func (*SocketOptions) SetCloseOnBeforeunload

func (s *SocketOptions) SetCloseOnBeforeunload(closeOnBeforeunload bool)

func (*SocketOptions) SetExtraHeaders

func (s *SocketOptions) SetExtraHeaders(extraHeaders http.Header)

func (*SocketOptions) SetForceBase64

func (s *SocketOptions) SetForceBase64(forceBase64 bool)

func (*SocketOptions) SetHost

func (s *SocketOptions) SetHost(host string)

func (*SocketOptions) SetHostname

func (s *SocketOptions) SetHostname(hostname string)

func (*SocketOptions) SetPath

func (s *SocketOptions) SetPath(path string)

func (*SocketOptions) SetPerMessageDeflate

func (s *SocketOptions) SetPerMessageDeflate(perMessageDeflate *types.PerMessageDeflate)

func (*SocketOptions) SetPort

func (s *SocketOptions) SetPort(port string)

func (*SocketOptions) SetProtocols

func (s *SocketOptions) SetProtocols(protocols []string)

func (*SocketOptions) SetQUICConfig

func (s *SocketOptions) SetQUICConfig(quicConfig *quic.Config)

func (*SocketOptions) SetQuery

func (s *SocketOptions) SetQuery(query url.Values)

func (*SocketOptions) SetRememberUpgrade

func (s *SocketOptions) SetRememberUpgrade(rememberUpgrade bool)

func (*SocketOptions) SetRequestTimeout

func (s *SocketOptions) SetRequestTimeout(requestTimeout time.Duration)

func (*SocketOptions) SetSecure

func (s *SocketOptions) SetSecure(secure bool)

func (*SocketOptions) SetTLSClientConfig

func (s *SocketOptions) SetTLSClientConfig(tlsClientConfig *tls.Config)

func (*SocketOptions) SetTimestampParam

func (s *SocketOptions) SetTimestampParam(timestampParam string)

func (*SocketOptions) SetTimestampRequests

func (s *SocketOptions) SetTimestampRequests(timestampRequests bool)

func (*SocketOptions) SetTransportOptions

func (s *SocketOptions) SetTransportOptions(transportOptions map[string]SocketOptionsInterface)

func (*SocketOptions) SetTransports

func (s *SocketOptions) SetTransports(transports *types.Set[TransportCtor])

func (*SocketOptions) SetTryAllTransports

func (s *SocketOptions) SetTryAllTransports(tryAllTransports bool)

func (*SocketOptions) SetUpgrade

func (s *SocketOptions) SetUpgrade(upgrade bool)

func (*SocketOptions) SetUseNativeTimers

func (s *SocketOptions) SetUseNativeTimers(useNativeTimers bool)

func (*SocketOptions) SetWithCredentials

func (s *SocketOptions) SetWithCredentials(withCredentials bool)

func (*SocketOptions) TLSClientConfig

func (s *SocketOptions) TLSClientConfig() *tls.Config

func (*SocketOptions) TimestampParam

func (s *SocketOptions) TimestampParam() string

func (*SocketOptions) TimestampRequests

func (s *SocketOptions) TimestampRequests() bool

func (*SocketOptions) TransportOptions

func (s *SocketOptions) TransportOptions() map[string]SocketOptionsInterface

func (*SocketOptions) Transports

func (s *SocketOptions) Transports() *types.Set[TransportCtor]

func (*SocketOptions) TryAllTransports

func (s *SocketOptions) TryAllTransports() bool

func (*SocketOptions) Upgrade

func (s *SocketOptions) Upgrade() bool

func (*SocketOptions) UseNativeTimers

func (s *SocketOptions) UseNativeTimers() bool

func (*SocketOptions) WithCredentials

func (s *SocketOptions) WithCredentials() bool

type SocketOptionsInterface

type SocketOptionsInterface interface {
	Host() string
	GetRawHost() *string
	SetHost(string)

	Hostname() string
	GetRawHostname() *string
	SetHostname(string)

	Secure() bool
	GetRawSecure() *bool
	SetSecure(bool)

	Port() string
	GetRawPort() *string
	SetPort(string)

	Query() url.Values
	GetRawQuery() url.Values
	SetQuery(url.Values)

	Agent() string
	GetRawAgent() *string
	SetAgent(string)

	Upgrade() bool
	GetRawUpgrade() *bool
	SetUpgrade(bool)

	ForceBase64() bool
	GetRawForceBase64() *bool
	SetForceBase64(bool)

	TimestampParam() string
	GetRawTimestampParam() *string
	SetTimestampParam(string)

	TimestampRequests() bool
	GetRawTimestampRequests() *bool
	SetTimestampRequests(bool)

	Transports() *types.Set[TransportCtor]
	GetRawTransports() *types.Set[TransportCtor]
	SetTransports(*types.Set[TransportCtor])

	TryAllTransports() bool
	GetRawTryAllTransports() *bool
	SetTryAllTransports(bool)

	RememberUpgrade() bool
	GetRawRememberUpgrade() *bool
	SetRememberUpgrade(bool)

	RequestTimeout() time.Duration
	GetRawRequestTimeout() *time.Duration
	SetRequestTimeout(time.Duration)

	TransportOptions() map[string]SocketOptionsInterface
	GetRawTransportOptions() map[string]SocketOptionsInterface
	SetTransportOptions(map[string]SocketOptionsInterface)

	TLSClientConfig() *tls.Config
	GetRawTLSClientConfig() *tls.Config
	SetTLSClientConfig(*tls.Config)

	QUICConfig() *quic.Config
	GetRawQUICConfig() *quic.Config
	SetQUICConfig(*quic.Config)

	ExtraHeaders() http.Header
	GetRawExtraHeaders() http.Header
	SetExtraHeaders(http.Header)

	WithCredentials() bool
	GetRawWithCredentials() *bool
	SetWithCredentials(bool)

	UseNativeTimers() bool
	GetRawUseNativeTimers() *bool
	SetUseNativeTimers(bool)

	AutoUnref() bool
	GetRawAutoUnref() *bool
	SetAutoUnref(bool)

	CloseOnBeforeunload() bool
	GetRawCloseOnBeforeunload() *bool
	SetCloseOnBeforeunload(bool)

	PerMessageDeflate() *types.PerMessageDeflate
	GetRawPerMessageDeflate() *types.PerMessageDeflate
	SetPerMessageDeflate(*types.PerMessageDeflate)

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

	AddTrailingSlash() bool
	GetRawAddTrailingSlash() *bool
	SetAddTrailingSlash(addTrailingSlash bool)

	Protocols() []string
	GetRawProtocols() []string
	SetProtocols([]string)
}

SocketOptionsInterface defines the configuration interface for Socket connections. It provides methods to get and set various connection parameters including host, port, security settings, and transport options.

type SocketState

type SocketState string

SocketState represents the current state of a Socket connection. This is used to track the lifecycle of the socket connection.

const (
	// SocketStateOpening indicates that the socket is in the process of establishing
	// a connection with the server.
	SocketStateOpening SocketState = "opening"

	// SocketStateOpen indicates that the socket has successfully established a
	// connection with the server and is ready for communication.
	SocketStateOpen SocketState = "open"

	// SocketStateClosing indicates that the socket is in the process of closing
	// its connection with the server.
	SocketStateClosing SocketState = "closing"

	// SocketStateClosed indicates that the socket has completely closed its
	// connection with the server.
	SocketStateClosed SocketState = "closed"
)

type SocketWithUpgrade

type SocketWithUpgrade interface {
	SocketWithoutUpgrade
}

SocketWithUpgrade extends SocketWithoutUpgrade to add transport upgrade capabilities. This implementation will attempt to upgrade the initial transport to a more efficient one after the connection is established.

Key features:

  • Automatic transport upgrade mechanism
  • Fallback to lower-level transports if upgrade fails
  • Event-based communication
  • Support for binary data

Example usage:

socket := NewSocketWithUpgrade("http://localhost:8080", &SocketOptions{
    Transports: types.NewSet[string](transports.WEBSOCKET),
})

socket.On("open", func() {
    socket.Send("hello")
})

Events:

  • "open": Emitted when the connection is established
  • "close": Emitted when the connection is closed
  • "error": Emitted when an error occurs
  • "message": Emitted when data is received
  • "upgrade": Emitted when transport upgrade is successful
  • "upgradeError": Emitted when transport upgrade fails

See: SocketWithoutUpgrade for the base implementation without upgrade support See: Socket for the recommended high-level interface

func MakeSocketWithUpgrade

func MakeSocketWithUpgrade() SocketWithUpgrade

MakeSocketWithUpgrade creates a new socket instance with upgrade support. It initializes the base socket and prepares the upgrade mechanism.

Returns:

  • SocketWithUpgrade: A new socket instance with upgrade capabilities

func NewSocketWithUpgrade

func NewSocketWithUpgrade(uri string, opts SocketOptionsInterface) SocketWithUpgrade

NewSocketWithUpgrade creates a new socket with the specified URI and options.

Parameters:

Returns:

  • SocketWithUpgrade: A configured socket instance

type SocketWithoutUpgrade

type SocketWithoutUpgrade interface {
	// EventEmitter provides event-based communication capabilities
	types.EventEmitter

	// Prototype sets the prototype interface for method rewriting
	Prototype(SocketWithoutUpgrade)

	// Proto returns the prototype interface instance
	Proto() SocketWithoutUpgrade

	// SetPriorWebsocketSuccess updates the WebSocket success state
	// This is used to optimize future connection attempts
	SetPriorWebsocketSuccess(bool)

	// SetUpgrading updates the upgrading state of the socket
	// This indicates whether a transport upgrade is in progress
	SetUpgrading(bool)

	// Id returns the unique identifier for this socket connection
	Id() string

	// Transport returns the current transport being used
	Transport() Transport

	// ReadyState returns the current state of the socket connection
	ReadyState() SocketState

	// WriteBuffer returns the packet buffer for queued writes
	WriteBuffer() *types.Slice[*packet.Packet]

	// Opts returns the socket options configuration
	Opts() SocketOptionsInterface

	// Transports returns the set of available transport types
	Transports() *types.Set[string]

	// Upgrading returns whether a transport upgrade is in progress
	Upgrading() bool

	// CookieJar returns the cookie jar used for HTTP requests
	CookieJar() http.CookieJar

	// PriorWebsocketSuccess returns whether previous WebSocket connections were successful
	PriorWebsocketSuccess() bool

	// Protocol returns the Engine.IO protocol version being used
	Protocol() int

	// Construct initializes the socket with the given URI and options
	Construct(string, SocketOptionsInterface)

	// CreateTransport creates a new transport instance of the specified type
	CreateTransport(string) Transport

	// SetTransport updates the current transport being used
	SetTransport(Transport)

	// OnOpen handles the socket open event
	OnOpen()

	// OnHandshake handles the initial handshake data from the server
	OnHandshake(*HandshakeData)

	// Flush sends all queued packets in the write buffer
	Flush()

	// HasPingExpired checks if the current ping timeout has expired
	HasPingExpired() bool

	// Write queues data to be sent to the server
	// Parameters:
	//   - data: The data to send
	//   - options: Optional packet configuration
	//   - callback: Optional callback to be called after the write completes
	Write(io.Reader, *packet.Options, func()) SocketWithoutUpgrade

	// Send is an alias for Write
	Send(io.Reader, *packet.Options, func()) SocketWithoutUpgrade

	// Close terminates the socket connection
	Close() SocketWithoutUpgrade
}

SocketWithoutUpgrade provides a WebSocket-like interface to connect to an Engine.IO server. This implementation maintains a single transport connection without attempting to upgrade to more efficient transports after initial connection.

Key features:

  • Single transport connection (no upgrade mechanism)
  • Event-based communication
  • Support for binary data
  • Tree-shaking friendly (transports must be explicitly included)

Example usage:

socket := NewSocketWithoutUpgrade("http://localhost:8080", &SocketOptions{
    Transports: types.NewSet[string](transports.WEBSOCKET),
})

socket.On(SocketStateOpen, func() {
    socket.Send("hello")
})

See: SocketWithUpgrade for an implementation with transport upgrade support See: Socket for the recommended high-level interface

func MakeSocketWithoutUpgrade

func MakeSocketWithoutUpgrade() SocketWithoutUpgrade

MakeSocketWithoutUpgrade creates a new socketWithoutUpgrade instance with default settings. It initializes the basic socket structure without establishing a connection.

func NewSocketWithoutUpgrade

func NewSocketWithoutUpgrade(uri string, opts SocketOptionsInterface) SocketWithoutUpgrade

NewSocketWithoutUpgrade creates and initializes a new socket connection. It takes a URI string and optional socket options to configure the connection.

type Transport

type Transport interface {
	// EventEmitter provides event-based communication capabilities
	types.EventEmitter

	// Prototype sets the prototype interface for method rewriting
	Prototype(Transport)

	// Proto returns the prototype interface instance
	Proto() Transport

	// SetWritable updates whether the transport can send data
	SetWritable(bool)

	// SetReadyState updates the current state of the transport
	SetReadyState(TransportState)

	// Name returns the identifier for this transport type
	Name() string

	// Query returns the URL query parameters for the transport
	Query() url.Values

	// Writable returns whether the transport can currently send data
	Writable() bool

	// Opts returns the socket options configuration
	Opts() SocketOptionsInterface

	// SupportsBinary returns whether the transport supports binary data
	SupportsBinary() bool

	// ReadyState returns the current state of the transport
	ReadyState() TransportState

	// Socket returns the parent socket instance
	Socket() Socket

	// Construct initializes the transport with the given socket and options
	Construct(Socket, SocketOptionsInterface)

	// OnError handles transport-level errors
	OnError(string, error, context.Context) Transport

	// Open initiates the transport connection
	Open() Transport

	// Close terminates the transport connection
	Close() Transport

	// Send transmits packets through the transport
	Send([]*packet.Packet)

	// OnOpen handles successful connection establishment
	OnOpen()

	// OnData processes incoming raw data
	OnData(types.BufferInterface)

	// OnPacket handles decoded packets
	OnPacket(*packet.Packet)

	// OnClose handles connection termination
	OnClose(error)

	// Pause temporarily suspends the transport
	Pause(func())

	// CreateUri constructs a URL for the transport connection
	CreateUri(string, url.Values) *url.URL

	// DoOpen implements transport-specific connection initialization
	DoOpen()

	// DoClose implements transport-specific connection termination
	DoClose()

	// Write implements transport-specific packet transmission
	Write([]*packet.Packet)
}

Transport defines the interface for all transport implementations in Engine.IO. It provides a common set of methods that all transport types (WebSocket, HTTP long-polling, WebTransport) must implement to ensure consistent behavior across different transport mechanisms.

The Transport interface is designed to be transport-agnostic, allowing different transport implementations to provide their specific functionality while maintaining a consistent API for the higher-level socket layer.

func MakeTransport

func MakeTransport() Transport

MakeTransport creates a new transport instance with default settings. This is the factory function for creating a new transport.

Returns:

  • Transport: A new transport instance initialized with default settings

func NewTransport

func NewTransport(socket Socket, opts SocketOptionsInterface) Transport

NewTransport creates a new transport instance with the specified socket and options.

Parameters:

  • socket: The parent socket instance
  • opts: The socket options configuration

Returns:

  • Transport: A new transport instance configured with the specified options

type TransportCtor

type TransportCtor interface {
	// Name returns the identifier for this transport type.
	// This is used to identify the transport in configuration and upgrade processes.
	Name() string

	// New creates a new transport instance with the specified socket and options.
	//
	// Parameters:
	//   - socket: The parent socket instance
	//   - opts: The socket options configuration
	//
	// Returns: A new Transport instance
	New(Socket, SocketOptionsInterface) Transport
}

TransportCtor defines the interface for transport constructors. This interface is used to create new transport instances with specific configurations.

type TransportState

type TransportState string

TransportState represents the current state of a Transport connection. This is used to track the lifecycle of individual transport connections.

const (
	// TransportStateOpening indicates that the transport is in the process of
	// establishing a connection.
	TransportStateOpening TransportState = "opening"

	// TransportStateOpen indicates that the transport has successfully established
	// a connection and is ready for communication.
	TransportStateOpen TransportState = "open"

	// TransportStateClosed indicates that the transport has completely closed its
	// connection.
	TransportStateClosed TransportState = "closed"

	// TransportStatePausing indicates that the transport is in the process of
	// temporarily suspending its connection. This is typically used during
	// transport upgrades.
	TransportStatePausing TransportState = "pausing"

	// TransportStatePaused indicates that the transport has temporarily suspended
	// its connection. This state is maintained during transport upgrades.
	TransportStatePaused TransportState = "paused"
)

type WebSocket

type WebSocket interface {
	Transport
}

WebSocket represents the WebSocket transport type. This transport provides full-duplex communication over a single TCP connection, offering better performance than polling.

Features:

  • Full-duplex communication
  • Lower latency than polling
  • Binary data support
  • Built-in heartbeat mechanism
  • Automatic reconnection

func MakeWebSocket

func MakeWebSocket() WebSocket

MakeWebSocket creates a new WebSocket transport instance with default settings. This is the factory function for creating a new WebSocket transport.

Returns:

  • WebSocket: A new WebSocket transport instance initialized with default settings

func NewWebSocket

func NewWebSocket(socket Socket, opts SocketOptionsInterface) WebSocket

NewWebSocket creates a new WebSocket transport instance with the specified socket and options.

Parameters:

  • socket: The parent socket instance
  • opts: The socket options configuration

Returns:

  • WebSocket: A new WebSocket transport instance configured with the specified options

type WebSocketBuilder

type WebSocketBuilder struct{}

WebSocketBuilder implements the transport builder pattern for WebSocket connections. It provides a factory method for creating new WebSocket transport instances.

func (*WebSocketBuilder) Name

func (*WebSocketBuilder) Name() string

Name returns the identifier for the WebSocket transport type.

Returns:

  • string: The transport name ("websocket")

func (*WebSocketBuilder) New

New creates a new WebSocket transport instance.

Parameters:

  • socket: The parent socket instance
  • opts: The socket options configuration

Returns:

  • Transport: A new WebSocket transport instance

type WebTransport

type WebTransport interface {
	Transport
}

WebTransport represents the WebTransport transport type. This transport provides low-latency, bidirectional communication using the QUIC protocol, offering several advantages over WebSocket.

Features:

  • Lower latency than WebSocket
  • Better multiplexing support
  • Built-in congestion control
  • Support for unreliable datagrams
  • Independent streams for parallel data transfer
  • Modern security features

Note: WebTransport requires browser support and a compatible server. See: https://developer.mozilla.org/en-US/docs/Web/API/WebTransport See: https://caniuse.com/webtransport

func MakeWebTransport

func MakeWebTransport() WebTransport

MakeWebTransport creates a new WebTransport instance with default settings. This is the factory function for creating a new WebTransport.

func NewWebTransport

func NewWebTransport(socket Socket, opts SocketOptionsInterface) WebTransport

NewWebTransport creates a new WebTransport instance with the specified socket and options.

Parameters:

  • socket: The parent socket instance
  • opts: The socket options configuration

Returns: A new WebTransport instance

type WebTransportBuilder

type WebTransportBuilder struct{}

WebTransportBuilder implements the transport builder pattern for WebTransport connections. It provides a factory method for creating new WebTransport instances.

func (*WebTransportBuilder) Name

func (*WebTransportBuilder) Name() string

Name returns the identifier for the WebTransport transport type.

Returns:

  • string: The transport name ("webtransport")

func (*WebTransportBuilder) New

New creates a new WebTransport instance.

Parameters:

  • socket: The parent socket instance
  • opts: The socket options configuration

Returns:

  • Transport: A new WebTransport instance

Jump to

Keyboard shortcuts

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