Documentation
¶
Index ¶
- Constants
- Variables
- type Ack
- type Adapter
- type AdapterBuilder
- type AdapterConstructor
- type BroadcastFlags
- type BroadcastOperator
- func (b *BroadcastOperator) Compress(compress bool) *BroadcastOperator
- func (b *BroadcastOperator) Construct(adapter Adapter, rooms *types.Set[Room], exceptRooms *types.Set[Room], ...)
- func (b *BroadcastOperator) DisconnectSockets(status bool)
- func (b *BroadcastOperator) Emit(ev string, args ...any) error
- func (b *BroadcastOperator) EmitWithAck(ev string, args ...any) func(Ack)
- func (b *BroadcastOperator) Except(room ...Room) *BroadcastOperator
- func (b *BroadcastOperator) FetchSockets() func(func([]*RemoteSocket, error))
- func (b *BroadcastOperator) In(room ...Room) *BroadcastOperator
- func (b *BroadcastOperator) Local() *BroadcastOperator
- func (b *BroadcastOperator) SocketsJoin(room ...Room)
- func (b *BroadcastOperator) SocketsLeave(room ...Room)
- func (b *BroadcastOperator) Timeout(timeout time.Duration) *BroadcastOperator
- func (b *BroadcastOperator) To(room ...Room) *BroadcastOperator
- func (b *BroadcastOperator) Volatile() *BroadcastOperator
- type BroadcastOptions
- type Client
- type ConnectionStateRecovery
- func (c *ConnectionStateRecovery) Assign(data ConnectionStateRecoveryInterface) ConnectionStateRecoveryInterface
- func (c *ConnectionStateRecovery) GetRawMaxDisconnectionDuration() types.Optional[int64]
- func (c *ConnectionStateRecovery) GetRawSkipMiddlewares() types.Optional[bool]
- func (c *ConnectionStateRecovery) MaxDisconnectionDuration() int64
- func (c *ConnectionStateRecovery) SetMaxDisconnectionDuration(maxDisconnectionDuration int64)
- func (c *ConnectionStateRecovery) SetSkipMiddlewares(skipMiddlewares bool)
- func (c *ConnectionStateRecovery) SkipMiddlewares() bool
- type ConnectionStateRecoveryInterface
- type ExtendedError
- type Handshake
- type Namespace
- type NamespaceMiddleware
- type ParentBroadcastAdapter
- type ParentBroadcastAdapterBuilder
- type ParentNamespace
- type ParentNspNameMatchFn
- type PersistedPacket
- type PollingBuilder
- type PrivateSessionId
- type RemoteSocket
- func (r *RemoteSocket) Construct(adapter Adapter, details SocketDetails)
- func (r *RemoteSocket) Data() any
- func (r *RemoteSocket) Disconnect(status bool) *RemoteSocket
- func (r *RemoteSocket) Emit(ev string, args ...any) error
- func (r *RemoteSocket) Handshake() *Handshake
- func (r *RemoteSocket) Id() SocketId
- func (r *RemoteSocket) Join(room ...Room)
- func (r *RemoteSocket) Leave(room ...Room)
- func (r *RemoteSocket) Rooms() *types.Set[Room]
- func (r *RemoteSocket) Timeout(timeout time.Duration) *BroadcastOperator
- type Room
- type Server
- func (s *Server) Adapter() AdapterConstructor
- func (s *Server) Attach(srv any, opts *ServerOptions) *Server
- func (s *Server) Bind(egs engine.BaseServer) *Server
- func (s *Server) Close(fn func(error))
- func (s *Server) Compress(compress bool) *BroadcastOperator
- func (s *Server) ConnectTimeout() time.Duration
- func (s *Server) Construct(srv any, opts ServerOptionsInterface)
- func (s *Server) DisconnectSockets(status bool)
- func (s *Server) Emit(ev string, args ...any) *Server
- func (s *Server) Encoder() parser.Encoder
- func (s *Server) Engine() engine.BaseServer
- func (s *Server) Except(room ...Room) *BroadcastOperator
- func (s *Server) FetchSockets() func(func([]*RemoteSocket, error))
- func (s *Server) In(room ...Room) *BroadcastOperator
- func (s *Server) Listen(srv any, opts *ServerOptions) *Server
- func (s *Server) Local() *BroadcastOperator
- func (s *Server) Of(name any, fn types.EventListener) Namespace
- func (s *Server) Opts() ServerOptionsInterface
- func (s *Server) Path() string
- func (s *Server) Send(args ...any) *Server
- func (s *Server) ServeClient() bool
- func (s *Server) ServeHandler(opts *ServerOptions) http.Handler
- func (s *Server) ServerSideEmit(ev string, args ...any) error
- func (s *Server) ServerSideEmitWithAck(ev string, args ...any) func(Ack) error
- func (s *Server) SetAdapter(v AdapterConstructor) *Server
- func (s *Server) SetConnectTimeout(v time.Duration) *Server
- func (s *Server) SetPath(v string) *Server
- func (s *Server) SetServeClient(v bool) *Server
- func (s *Server) Sockets() Namespace
- func (s *Server) SocketsJoin(room ...Room)
- func (s *Server) SocketsLeave(room ...Room)
- func (s *Server) Timeout(timeout time.Duration) *BroadcastOperator
- func (s *Server) To(room ...Room) *BroadcastOperator
- func (s *Server) Use(fn NamespaceMiddleware) *Server
- func (s *Server) Volatile() *BroadcastOperator
- func (s *Server) Write(args ...any) *Server
- type ServerOptions
- func (s *ServerOptions) Adapter() AdapterConstructor
- func (s *ServerOptions) Assign(data ServerOptionsInterface) ServerOptionsInterface
- func (s *ServerOptions) CleanupEmptyChildNamespaces() bool
- func (s *ServerOptions) ClientVersion() string
- func (s *ServerOptions) ConnectTimeout() time.Duration
- func (s *ServerOptions) ConnectionStateRecovery() ConnectionStateRecoveryInterface
- func (s *ServerOptions) GetRawAdapter() types.Optional[AdapterConstructor]
- func (s *ServerOptions) GetRawCleanupEmptyChildNamespaces() types.Optional[bool]
- func (s *ServerOptions) GetRawClientVersion() types.Optional[string]
- func (s *ServerOptions) GetRawConnectTimeout() types.Optional[time.Duration]
- func (s *ServerOptions) GetRawConnectionStateRecovery() types.Optional[ConnectionStateRecoveryInterface]
- func (s *ServerOptions) GetRawParser() types.Optional[parser.Parser]
- func (s *ServerOptions) GetRawServeClient() types.Optional[bool]
- func (s *ServerOptions) Parser() parser.Parser
- func (s *ServerOptions) ServeClient() bool
- func (s *ServerOptions) SetAdapter(adapter AdapterConstructor)
- func (s *ServerOptions) SetCleanupEmptyChildNamespaces(cleanupEmptyChildNamespaces bool)
- func (s *ServerOptions) SetClientVersion(clientVersion string)
- func (s *ServerOptions) SetConnectTimeout(connectTimeout time.Duration)
- func (s *ServerOptions) SetConnectionStateRecovery(connectionStateRecovery ConnectionStateRecoveryInterface)
- func (s *ServerOptions) SetParser(parser parser.Parser)
- func (s *ServerOptions) SetServeClient(serveClient bool)
- type ServerOptionsInterface
- type Session
- type SessionAwareAdapter
- type SessionAwareAdapterBuilder
- type SessionData
- type SessionToPersist
- type SessionWithTimestamp
- type Socket
- func (s *Socket) Acks() *types.Map[uint64, Ack]
- func (s *Socket) Broadcast() *BroadcastOperator
- func (s *Socket) Client() *Client
- func (s *Socket) Compress(compress bool) *Socket
- func (s *Socket) Conn() engine.Socket
- func (s *Socket) Connected() bool
- func (s *Socket) Construct(nsp Namespace, client *Client, auth map[string]any, previousSession *Session)
- func (s *Socket) Data() any
- func (s *Socket) Disconnect(status bool) *Socket
- func (s *Socket) Disconnected() bool
- func (s *Socket) Emit(ev string, args ...any) error
- func (s *Socket) EmitWithAck(ev string, args ...any) func(Ack)
- func (s *Socket) Except(room ...Room) *BroadcastOperator
- func (s *Socket) Handshake() *Handshake
- func (s *Socket) Id() SocketId
- func (s *Socket) In(room ...Room) *BroadcastOperator
- func (s *Socket) Join(rooms ...Room)
- func (s *Socket) Leave(room Room)
- func (s *Socket) ListenersAny() []types.EventListener
- func (s *Socket) ListenersAnyOutgoing() []types.EventListener
- func (s *Socket) Local() *BroadcastOperator
- func (s *Socket) NotifyOutgoingListeners() func(*parser.Packet)
- func (s *Socket) Nsp() Namespace
- func (s *Socket) OffAny(listener types.EventListener) *Socket
- func (s *Socket) OffAnyOutgoing(listener types.EventListener) *Socket
- func (s *Socket) OnAny(listener types.EventListener) *Socket
- func (s *Socket) OnAnyOutgoing(listener types.EventListener) *Socket
- func (s *Socket) PrependAny(listener types.EventListener) *Socket
- func (s *Socket) PrependAnyOutgoing(listener types.EventListener) *Socket
- func (s *Socket) Recovered() bool
- func (s *Socket) Request() *types.HttpContext
- func (s *Socket) Rooms() *types.Set[Room]
- func (s *Socket) Send(args ...any) *Socket
- func (s *Socket) SetData(data any)
- func (s *Socket) Timeout(timeout time.Duration) *Socket
- func (s *Socket) To(room ...Room) *BroadcastOperator
- func (s *Socket) Use(fn SocketMiddleware) *Socket
- func (s *Socket) Volatile() *Socket
- func (s *Socket) Write(args ...any) *Socket
- type SocketDetails
- type SocketId
- type SocketMiddleware
- type StrictEventEmitter
- func (s *StrictEventEmitter) Emit(ev string, args ...any)
- func (s *StrictEventEmitter) EmitReserved(ev string, args ...any)
- func (s *StrictEventEmitter) EmitUntyped(ev string, args ...any)
- func (s *StrictEventEmitter) Listeners(ev string) []types.EventListener
- func (s *StrictEventEmitter) On(ev string, listeners ...types.EventListener) error
- func (s *StrictEventEmitter) Once(ev string, listeners ...types.EventListener) error
- type TransportCtor
- type WebSocketBuilder
- type WebTransportBuilder
- type WriteOptions
Constants ¶
const VERSION = version.VERSION
Variables ¶
var ( SOCKET_RESERVED_EVENTS = types.NewSet("connect", "connect_error", "disconnect", "disconnecting", "newListener", "removeListener") RECOVERABLE_DISCONNECT_REASONS = types.NewSet("transport error", "transport close", "forced close", "ping timeout", "server shutting down", "forced server close") )
var (
NAMESPACE_RESERVED_EVENTS = types.NewSet("connect", "connection", "new_namespace")
)
Functions ¶
This section is empty.
Types ¶
type Adapter ¶
type Adapter interface {
types.EventEmitter
Prototype(Adapter)
Proto() Adapter
Rooms() *types.Map[Room, *types.Set[SocketId]]
Sids() *types.Map[SocketId, *types.Set[Room]]
Nsp() Namespace
// Construct() should be called after calling Prototype()
Construct(Namespace)
// To be overridden
Init()
// To be overridden
Close()
// Returns the number of Socket.IO servers in the cluster
ServerCount() int64
// Adds a socket to a list of room.
AddAll(SocketId, *types.Set[Room])
// Removes a socket from a room.
Del(SocketId, Room)
// Removes a socket from all rooms it's joined.
DelAll(SocketId)
// Broadcasts a packet.
//
// Options:
// - `Flags` {*BroadcastFlags} flags for this packet
// - `Except` {*types.Set[Room]} sids that should be excluded
// - `Rooms` {*types.Set[Room]} list of rooms to broadcast to
Broadcast(*parser.Packet, *BroadcastOptions)
// Broadcasts a packet and expects multiple acknowledgements.
//
// Options:
// - `Flags` {*BroadcastFlags} flags for this packet
// - `Except` {*types.Set[Room]} sids that should be excluded
// - `Rooms` {*types.Set[Room]} list of rooms to broadcast to
BroadcastWithAck(*parser.Packet, *BroadcastOptions, func(uint64), Ack)
// Gets a list of sockets by sid.
Sockets(*types.Set[Room]) *types.Set[SocketId]
// Gets the list of rooms a given socket has joined.
SocketRooms(SocketId) *types.Set[Room]
// Returns the matching socket instances
FetchSockets(*BroadcastOptions) func(func([]SocketDetails, error))
// Makes the matching socket instances join the specified rooms
AddSockets(*BroadcastOptions, []Room)
// Makes the matching socket instances leave the specified rooms
DelSockets(*BroadcastOptions, []Room)
// Makes the matching socket instances disconnect
DisconnectSockets(*BroadcastOptions, bool)
// Send a packet to the other Socket.IO servers in the cluster
ServerSideEmit([]any) error
// Save the client session in order to restore it upon reconnection.
PersistSession(*SessionToPersist)
// Restore the session and find the packets that were missed by the client.
RestoreSession(PrivateSessionId, string) (*Session, error)
}
func NewAdapter ¶
NewAdapter creates a new Adapter for the given Namespace.
type AdapterBuilder ¶
type AdapterBuilder struct {
}
AdapterBuilder is a builder for creating Adapter instances.
func (*AdapterBuilder) New ¶
func (*AdapterBuilder) New(nsp Namespace) Adapter
New creates a new Adapter for the given Namespace.
type AdapterConstructor ¶
type BroadcastFlags ¶
type BroadcastFlags struct {
WriteOptions
Local bool `json:"local" msgpack:"local"`
Broadcast bool `json:"broadcast" msgpack:"broadcast"`
Binary bool `json:"binary" msgpack:"binary"`
Timeout *time.Duration `json:"timeout,omitempty" msgpack:"timeout,omitempty"`
ExpectSingleResponse bool `json:"expectSingleResponse" msgpack:"expectSingleResponse"`
}
type BroadcastOperator ¶
type BroadcastOperator struct {
// contains filtered or unexported fields
}
BroadcastOperator is used to broadcast events to multiple clients.
func MakeBroadcastOperator ¶
func MakeBroadcastOperator() *BroadcastOperator
MakeBroadcastOperator creates a new instance of BroadcastOperator.
func NewBroadcastOperator ¶
func NewBroadcastOperator(adapter Adapter, rooms *types.Set[Room], exceptRooms *types.Set[Room], flags *BroadcastFlags) *BroadcastOperator
NewBroadcastOperator initializes a BroadcastOperator with the given parameters.
func (*BroadcastOperator) Compress ¶
func (b *BroadcastOperator) Compress(compress bool) *BroadcastOperator
Compress sets the compress flag for subsequent event emissions.
func (*BroadcastOperator) Construct ¶
func (b *BroadcastOperator) Construct(adapter Adapter, rooms *types.Set[Room], exceptRooms *types.Set[Room], flags *BroadcastFlags)
Construct initializes the BroadcastOperator with the given parameters.
func (*BroadcastOperator) DisconnectSockets ¶
func (b *BroadcastOperator) DisconnectSockets(status bool)
DisconnectSockets makes the matching socket instances disconnect.
func (*BroadcastOperator) Emit ¶
func (b *BroadcastOperator) Emit(ev string, args ...any) error
Emit broadcasts an event to all connected clients.
func (*BroadcastOperator) EmitWithAck ¶
func (b *BroadcastOperator) EmitWithAck(ev string, args ...any) func(Ack)
EmitWithAck broadcasts an event and waits for acknowledgements from all clients.
func (*BroadcastOperator) Except ¶
func (b *BroadcastOperator) Except(room ...Room) *BroadcastOperator
Except excludes a room when emitting events. Returns a new BroadcastOperator for chaining.
func (*BroadcastOperator) FetchSockets ¶
func (b *BroadcastOperator) FetchSockets() func(func([]*RemoteSocket, error))
FetchSockets returns a function to fetch matching socket instances.
func (*BroadcastOperator) In ¶
func (b *BroadcastOperator) In(room ...Room) *BroadcastOperator
In targets a room when emitting events. Alias of To().
func (*BroadcastOperator) Local ¶
func (b *BroadcastOperator) Local() *BroadcastOperator
Local sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
func (*BroadcastOperator) SocketsJoin ¶
func (b *BroadcastOperator) SocketsJoin(room ...Room)
SocketsJoin makes the matching socket instances join the specified rooms.
func (*BroadcastOperator) SocketsLeave ¶
func (b *BroadcastOperator) SocketsLeave(room ...Room)
SocketsLeave makes the matching socket instances leave the specified rooms.
func (*BroadcastOperator) Timeout ¶
func (b *BroadcastOperator) Timeout(timeout time.Duration) *BroadcastOperator
Timeout adds a timeout for the next operation.
func (*BroadcastOperator) To ¶
func (b *BroadcastOperator) To(room ...Room) *BroadcastOperator
To targets a room when emitting events. Returns a new BroadcastOperator for chaining.
func (*BroadcastOperator) Volatile ¶
func (b *BroadcastOperator) Volatile() *BroadcastOperator
Volatile sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages.
type BroadcastOptions ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a Socket.IO client connection.
func NewClient ¶
NewClient creates a new Client and initializes it with the given server and connection.
func (*Client) Request ¶
func (c *Client) Request() *types.HttpContext
Request returns the reference to the request that originated the Engine.IO connection.
func (*Client) WriteToEngine ¶
func (c *Client) WriteToEngine(encodedPackets []types.BufferInterface, opts *WriteOptions)
WriteToEngine writes encoded packets to the Engine.IO transport.
type ConnectionStateRecovery ¶
type ConnectionStateRecovery struct {
// contains filtered or unexported fields
}
func DefaultConnectionStateRecovery ¶
func DefaultConnectionStateRecovery() *ConnectionStateRecovery
func (*ConnectionStateRecovery) Assign ¶
func (c *ConnectionStateRecovery) Assign(data ConnectionStateRecoveryInterface) ConnectionStateRecoveryInterface
func (*ConnectionStateRecovery) GetRawMaxDisconnectionDuration ¶
func (c *ConnectionStateRecovery) GetRawMaxDisconnectionDuration() types.Optional[int64]
func (*ConnectionStateRecovery) GetRawSkipMiddlewares ¶
func (c *ConnectionStateRecovery) GetRawSkipMiddlewares() types.Optional[bool]
func (*ConnectionStateRecovery) MaxDisconnectionDuration ¶
func (c *ConnectionStateRecovery) MaxDisconnectionDuration() int64
func (*ConnectionStateRecovery) SetMaxDisconnectionDuration ¶
func (c *ConnectionStateRecovery) SetMaxDisconnectionDuration(maxDisconnectionDuration int64)
func (*ConnectionStateRecovery) SetSkipMiddlewares ¶
func (c *ConnectionStateRecovery) SetSkipMiddlewares(skipMiddlewares bool)
func (*ConnectionStateRecovery) SkipMiddlewares ¶
func (c *ConnectionStateRecovery) SkipMiddlewares() bool
type ExtendedError ¶
type ExtendedError struct {
// contains filtered or unexported fields
}
func NewExtendedError ¶
func NewExtendedError(message string, data any) *ExtendedError
func (*ExtendedError) Data ¶
func (e *ExtendedError) Data() any
func (*ExtendedError) Err ¶
func (e *ExtendedError) Err() error
func (*ExtendedError) Error ¶
func (e *ExtendedError) Error() string
type Handshake ¶
type Handshake struct {
// HTTP headers sent by the client
Headers types.IncomingHttpHeaders `json:"headers" msgpack:"headers"`
// Creation time as a human-readable string
Time string `json:"time" msgpack:"time"`
// Client's IP address
Address string `json:"address" msgpack:"address"`
// Indicates if the connection is cross-domain
Xdomain bool `json:"xdomain" msgpack:"xdomain"`
// Indicates if the connection is established over TLS/HTTPS
Secure bool `json:"secure" msgpack:"secure"`
// Creation time as a Unix timestamp (seconds since epoch)
Issued int64 `json:"issued" msgpack:"issued"`
// Full request URL
Url string `json:"url" msgpack:"url"`
// Query parameters
Query types.ParsedUrlQuery `json:"query" msgpack:"query"`
// Authentication data map[string]any or nil
Auth map[string]any `json:"auth" msgpack:"auth"`
}
Handshake represents the initial connection information exchanged between the client and server during the handshake process.
type Namespace ¶
type Namespace interface {
On(string, ...types.EventListener) error
Once(string, ...types.EventListener) error
EmitReserved(string, ...any)
EmitUntyped(string, ...any)
Listeners(string) []types.EventListener
Prototype(Namespace)
Proto() Namespace
EventEmitter() *StrictEventEmitter
Sockets() *types.Map[SocketId, *Socket]
Server() *Server
Adapter() Adapter
Name() string
Ids() uint64
Fns() *types.Slice[NamespaceMiddleware]
// Construct() should be called after calling Prototype()
Construct(*Server, string)
// Initializes the `Adapter` for n nsp.
// Run upon changing adapter by `Server.Adapter`
// in addition to the constructor.
InitAdapter()
// Whether to remove child namespaces that have no sockets connected to them
Cleanup(types.Callable)
// Sets up namespace middleware.
Use(NamespaceMiddleware) Namespace
// Targets a room when emitting.
To(...Room) *BroadcastOperator
// Targets a room when emitting.
In(...Room) *BroadcastOperator
// Excludes a room when emitting.
Except(...Room) *BroadcastOperator
// Adds a new client.
Add(*Client, map[string]any, func(*Socket))
// Emits to all clients.
Emit(string, ...any) error
// Sends a `message` event to all clients.
Send(...any) Namespace
// Sends a `message` event to all clients.
Write(...any) Namespace
// Emit a packet to other Socket.IO servers
ServerSideEmit(string, ...any) error
// Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
ServerSideEmitWithAck(string, ...any) func(Ack) error
// Called when a packet is received from another Socket.IO server
OnServerSideEmit([]any)
// Sets the compress flag.
Compress(bool) *BroadcastOperator
// Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
// receive messages (because of network slowness or other issues, or because they’re connected through long polling
// and is in the middle of a request-response cycle).
Volatile() *BroadcastOperator
// Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
Local() *BroadcastOperator
// Adds a timeout in milliseconds for the next operation
Timeout(time.Duration) *BroadcastOperator
// Returns the matching socket instances
FetchSockets() func(func([]*RemoteSocket, error))
// Makes the matching socket instances join the specified rooms
SocketsJoin(...Room)
// Makes the matching socket instances leave the specified rooms
SocketsLeave(...Room)
// Makes the matching socket instances disconnect
DisconnectSockets(bool)
// Removes a client. Called by each [Socket].
Remove(*Socket)
}
A namespace is a communication channel that allows you to split the logic of your application over a single shared connection.
Each namespace has its own:
- event handlers
io.Of("/orders").On("connection", func(args ...any) {
socket := args[0].(*socket.Socket)
socket.On("order:list", func(...any){})
socket.On("order:create", func(...any){})
})
io.Of("/users").On("connection", func(args ...any) {
socket := args[0].(*socket.Socket)
socket.On("user:list", func(...any){})
})
- rooms
orderNamespace := io.Of("/orders")
orderNamespace.On("connection", func(args ...any) {
socket := args[0].(*socket.Socket)
socket.Join("room1")
orderNamespace.To("room1").Emit("hello")
})
userNamespace := io.Of("/users")
userNamespace.On("connection", func(args ...any) {
socket := args[0].(*socket.Socket)
socket.Join("room1") // distinct from the room in the "orders" namespace
userNamespace.To("room1").Emit("holà")
})
- middlewares
orderNamespace := io.Of("/orders")
orderNamespace.Use(func(socket *socket.Socket, next func(*socket.ExtendedError)) {
// ensure the socket has access to the "orders" namespace
})
userNamespace := io.Of("/users")
userNamespace.Use(func(socket *socket.Socket, next func(*socket.ExtendedError)) {
// ensure the socket has access to the "users" namespace
})
func MakeNamespace ¶
func MakeNamespace() Namespace
func NewNamespace ¶
type NamespaceMiddleware ¶
type NamespaceMiddleware = func(*Socket, func(*ExtendedError))
type ParentBroadcastAdapter ¶
type ParentBroadcastAdapter interface {
Adapter
}
func MakeParentBroadcastAdapter ¶
func MakeParentBroadcastAdapter() ParentBroadcastAdapter
func NewParentBroadcastAdapter ¶
func NewParentBroadcastAdapter(nsp Namespace) ParentBroadcastAdapter
type ParentBroadcastAdapterBuilder ¶
type ParentBroadcastAdapterBuilder struct {
}
func (*ParentBroadcastAdapterBuilder) New ¶
func (b *ParentBroadcastAdapterBuilder) New(nsp Namespace) Adapter
type ParentNamespace ¶
type ParentNamespace interface {
Namespace
Children() *types.Set[Namespace]
CreateChild(string) Namespace
}
func MakeParentNamespace ¶
func MakeParentNamespace() ParentNamespace
func NewParentNamespace ¶
func NewParentNamespace(server *Server) ParentNamespace
type ParentNspNameMatchFn ¶
type PersistedPacket ¶
type PersistedPacket struct {
Id string `json:"id" msgpack:"id"`
EmittedAt int64 `json:"emittedAt" msgpack:"emittedAt"`
Data any `json:"data" msgpack:"data"`
Opts *BroadcastOptions `json:"opts,omitempty" msgpack:"opts,omitempty"`
}
type PollingBuilder ¶
type PollingBuilder = transports.PollingBuilder
type PrivateSessionId ¶
type PrivateSessionId string
A private ID, sent by the server at the beginning of the Socket.IO session and used for connection state recovery upon reconnection
type RemoteSocket ¶
type RemoteSocket struct {
// contains filtered or unexported fields
}
Expose of subset of the attributes and methods of the Socket struct
func MakeRemoteSocket ¶
func MakeRemoteSocket() *RemoteSocket
func NewRemoteSocket ¶
func NewRemoteSocket(adapter Adapter, details SocketDetails) *RemoteSocket
func (*RemoteSocket) Construct ¶
func (r *RemoteSocket) Construct(adapter Adapter, details SocketDetails)
func (*RemoteSocket) Data ¶
func (r *RemoteSocket) Data() any
func (*RemoteSocket) Disconnect ¶
func (r *RemoteSocket) Disconnect(status bool) *RemoteSocket
Disconnect disconnects this client. If status is true, the underlying connection will be closed.
func (*RemoteSocket) Handshake ¶
func (r *RemoteSocket) Handshake() *Handshake
func (*RemoteSocket) Id ¶
func (r *RemoteSocket) Id() SocketId
func (*RemoteSocket) Join ¶
func (r *RemoteSocket) Join(room ...Room)
Join adds this remote socket to one or more rooms. The room parameter accepts one or more Room values.
func (*RemoteSocket) Leave ¶
func (r *RemoteSocket) Leave(room ...Room)
Leave removes this remote socket from one or more rooms. The room parameter accepts one or more Room values.
func (*RemoteSocket) Timeout ¶
func (r *RemoteSocket) Timeout(timeout time.Duration) *BroadcastOperator
Timeout sets a timeout for the next operation on this remote socket. The timeout parameter specifies the duration to wait for an acknowledgement.
type Room ¶
type Room string
we could extend the Room type to "string", but that would be a breaking change Related: https://github.com/socketio/socket.io-redis-adapter/issues/418
type Server ¶
type Server struct {
*StrictEventEmitter
// contains filtered or unexported fields
}
Represents a Socket.IO server.
import (
"github.com/zishang520/socket.io/v3/pkg/utils"
"github.com/zishang520/socket.io/servers/socket/v3"
)
io := socket.NewServer(nil, nil)
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
utils.Log().Info(`socket %s connected`, socket.Id())
// send an event to the client
socket.Emit("foo", "bar")
socket.On("foobar", func(...any) {
// an event was received from the client
})
// upon disconnection
socket.On("disconnect", func(reason ...any) {
utils.Log().Info(`socket %s disconnected due to %s`, socket.Id(), reason[0])
})
})
io.Listen(3000, nil)
func MakeServer ¶
func MakeServer() *Server
func NewServer ¶
func NewServer(srv any, opts ServerOptionsInterface) *Server
func (*Server) Adapter ¶
func (s *Server) Adapter() AdapterConstructor
func (*Server) Attach ¶
func (s *Server) Attach(srv any, opts *ServerOptions) *Server
Attach attaches socket.io to a server or port. srv is the server or port, opts are options passed to engine.io.
func (*Server) Bind ¶
func (s *Server) Bind(egs engine.BaseServer) *Server
Bind binds socket.io to an engine.io instance. egs is the engine.io (or compatible) server.
func (*Server) Close ¶
Close closes the server and all client connections. If fn is provided, it is called on error or when all connections are closed.
func (*Server) Compress ¶
func (s *Server) Compress(compress bool) *BroadcastOperator
Compress sets the compress flag for subsequent event emissions.
func (*Server) ConnectTimeout ¶
ConnectTimeout returns the current connect timeout duration.
func (*Server) Construct ¶
func (s *Server) Construct(srv any, opts ServerOptionsInterface)
func (*Server) DisconnectSockets ¶
DisconnectSockets makes the matching socket instances disconnect. If status is true, closes the underlying connection.
func (*Server) Engine ¶
func (s *Server) Engine() engine.BaseServer
func (*Server) Except ¶
func (s *Server) Except(room ...Room) *BroadcastOperator
Except excludes a room when emitting events. Returns a new BroadcastOperator for chaining.
func (*Server) FetchSockets ¶
func (s *Server) FetchSockets() func(func([]*RemoteSocket, error))
FetchSockets returns a function to fetch the matching socket instances.
func (*Server) In ¶
func (s *Server) In(room ...Room) *BroadcastOperator
In targets a room when emitting events. Returns a new BroadcastOperator for chaining.
func (*Server) Listen ¶
func (s *Server) Listen(srv any, opts *ServerOptions) *Server
Listen attaches socket.io to a server or port. srv is the server or port, opts are options passed to engine.io.
func (*Server) Local ¶
func (s *Server) Local() *BroadcastOperator
Local sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
func (*Server) Of ¶
func (s *Server) Of(name any, fn types.EventListener) Namespace
Of looks up a namespace by name or pattern and optionally registers a connection event handler. name can be a string, regexp, or ParentNspNameMatchFn; fn is the connection event handler.
func (*Server) Opts ¶
func (s *Server) Opts() ServerOptionsInterface
func (*Server) Send ¶
Send sends a "message" event to all clients. This mimics the WebSocket.send() method.
func (*Server) ServeClient ¶
ServeClient returns whether the server is serving client code.
func (*Server) ServeHandler ¶
func (s *Server) ServeHandler(opts *ServerOptions) http.Handler
ServeHandler returns an http.Handler for the server.
func (*Server) ServerSideEmit ¶
ServerSideEmit sends a message to other Socket.IO servers in the cluster. ev is the event name, args are the arguments (may include an acknowledgement callback).
func (*Server) ServerSideEmitWithAck ¶
ServerSideEmitWithAck sends a message and expects an acknowledgement from other Socket.IO servers in the cluster. Returns a function that will be fulfilled when all servers have acknowledged the event.
func (*Server) SetAdapter ¶
func (s *Server) SetAdapter(v AdapterConstructor) *Server
SetAdapter sets the adapter for rooms.
func (*Server) SetConnectTimeout ¶
SetConnectTimeout sets the delay after which a client without namespace is closed.
func (*Server) SetServeClient ¶
SetServeClient sets whether to serve the client code to browsers.
func (*Server) SocketsJoin ¶
SocketsJoin makes the matching socket instances join the specified rooms.
func (*Server) SocketsLeave ¶
SocketsLeave makes the matching socket instances leave the specified rooms.
func (*Server) Timeout ¶
func (s *Server) Timeout(timeout time.Duration) *BroadcastOperator
Timeout adds a timeout for the next operation.
func (*Server) To ¶
func (s *Server) To(room ...Room) *BroadcastOperator
To targets a room when emitting events. Returns a new BroadcastOperator for chaining.
func (*Server) Use ¶
func (s *Server) Use(fn NamespaceMiddleware) *Server
Use registers a middleware function that is executed for every incoming Socket.
func (*Server) Volatile ¶
func (s *Server) Volatile() *BroadcastOperator
Volatile sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages.
type ServerOptions ¶
func DefaultServerOptions ¶
func DefaultServerOptions() *ServerOptions
func (*ServerOptions) Adapter ¶
func (s *ServerOptions) Adapter() AdapterConstructor
func (*ServerOptions) Assign ¶
func (s *ServerOptions) Assign(data ServerOptionsInterface) ServerOptionsInterface
func (*ServerOptions) CleanupEmptyChildNamespaces ¶
func (s *ServerOptions) CleanupEmptyChildNamespaces() bool
func (*ServerOptions) ClientVersion ¶
func (s *ServerOptions) ClientVersion() string
func (*ServerOptions) ConnectTimeout ¶
func (s *ServerOptions) ConnectTimeout() time.Duration
func (*ServerOptions) ConnectionStateRecovery ¶
func (s *ServerOptions) ConnectionStateRecovery() ConnectionStateRecoveryInterface
func (*ServerOptions) GetRawAdapter ¶
func (s *ServerOptions) GetRawAdapter() types.Optional[AdapterConstructor]
func (*ServerOptions) GetRawCleanupEmptyChildNamespaces ¶
func (s *ServerOptions) GetRawCleanupEmptyChildNamespaces() types.Optional[bool]
func (*ServerOptions) GetRawClientVersion ¶
func (s *ServerOptions) GetRawClientVersion() types.Optional[string]
func (*ServerOptions) GetRawConnectTimeout ¶
func (s *ServerOptions) GetRawConnectTimeout() types.Optional[time.Duration]
func (*ServerOptions) GetRawConnectionStateRecovery ¶
func (s *ServerOptions) GetRawConnectionStateRecovery() types.Optional[ConnectionStateRecoveryInterface]
func (*ServerOptions) GetRawParser ¶
func (s *ServerOptions) GetRawParser() types.Optional[parser.Parser]
func (*ServerOptions) GetRawServeClient ¶
func (s *ServerOptions) GetRawServeClient() types.Optional[bool]
func (*ServerOptions) Parser ¶
func (s *ServerOptions) Parser() parser.Parser
func (*ServerOptions) ServeClient ¶
func (s *ServerOptions) ServeClient() bool
func (*ServerOptions) SetAdapter ¶
func (s *ServerOptions) SetAdapter(adapter AdapterConstructor)
func (*ServerOptions) SetCleanupEmptyChildNamespaces ¶
func (s *ServerOptions) SetCleanupEmptyChildNamespaces(cleanupEmptyChildNamespaces bool)
func (*ServerOptions) SetClientVersion ¶
func (s *ServerOptions) SetClientVersion(clientVersion string)
func (*ServerOptions) SetConnectTimeout ¶
func (s *ServerOptions) SetConnectTimeout(connectTimeout time.Duration)
func (*ServerOptions) SetConnectionStateRecovery ¶
func (s *ServerOptions) SetConnectionStateRecovery(connectionStateRecovery ConnectionStateRecoveryInterface)
func (*ServerOptions) SetParser ¶
func (s *ServerOptions) SetParser(parser parser.Parser)
func (*ServerOptions) SetServeClient ¶
func (s *ServerOptions) SetServeClient(serveClient bool)
type ServerOptionsInterface ¶
type ServerOptionsInterface interface {
config.OptionsInterface
SetServeClient(bool)
GetRawServeClient() types.Optional[bool]
ServeClient() bool
SetClientVersion(string)
GetRawClientVersion() types.Optional[string]
ClientVersion() string
SetAdapter(AdapterConstructor)
GetRawAdapter() types.Optional[AdapterConstructor]
Adapter() AdapterConstructor
SetParser(parser.Parser)
GetRawParser() types.Optional[parser.Parser]
Parser() parser.Parser
SetConnectTimeout(time.Duration)
GetRawConnectTimeout() types.Optional[time.Duration]
ConnectTimeout() time.Duration
SetConnectionStateRecovery(ConnectionStateRecoveryInterface)
GetRawConnectionStateRecovery() types.Optional[ConnectionStateRecoveryInterface]
ConnectionStateRecovery() ConnectionStateRecoveryInterface
SetCleanupEmptyChildNamespaces(bool)
GetRawCleanupEmptyChildNamespaces() types.Optional[bool]
CleanupEmptyChildNamespaces() bool
}
type Session ¶
type Session struct {
*SessionToPersist
MissedPackets []any `json:"missedPackets" msgpack:"missedPackets"`
}
type SessionAwareAdapter ¶
type SessionAwareAdapter interface {
Adapter
}
func MakeSessionAwareAdapter ¶
func MakeSessionAwareAdapter() SessionAwareAdapter
func NewSessionAwareAdapter ¶
func NewSessionAwareAdapter(nsp Namespace) SessionAwareAdapter
type SessionAwareAdapterBuilder ¶
type SessionAwareAdapterBuilder struct {
}
func (*SessionAwareAdapterBuilder) New ¶
func (*SessionAwareAdapterBuilder) New(nsp Namespace) Adapter
type SessionData ¶
type SessionData struct {
Pid any `json:"pid" msgpack:"pid"`
Offset any `json:"offset" msgpack:"offset"`
}
func (*SessionData) GetOffset ¶
func (s *SessionData) GetOffset() (offset string, ok bool)
func (*SessionData) GetPid ¶
func (s *SessionData) GetPid() (pid string, ok bool)
type SessionToPersist ¶
type SessionWithTimestamp ¶
type SessionWithTimestamp struct {
*SessionToPersist
DisconnectedAt int64 `json:"disconnectedAt" msgpack:"disconnectedAt"`
}
type Socket ¶
type Socket struct {
*StrictEventEmitter
// contains filtered or unexported fields
}
This is the main object for interacting with a client.
A Socket belongs to a given Namespace and uses an underlying Client to communicate.
Within each Namespace, you can also define arbitrary channels (called "rooms") that the Socket can join and leave. That provides a convenient way to broadcast to a group of socket instances.
io.On("connection", func(args ...any) {
socket := args[0].(*socket.Socket)
utils.Log().Info(`socket %s connected`, socket.Id())
// send an event to the client
socket.Emit("foo", "bar")
socket.On("foobar", func(...any) {
// an event was received from the client
})
// join the room named "room1"
socket.Join("room1")
// broadcast to everyone in the room named "room1"
io.to("room1").Emit("hello")
// upon disconnection
socket.On("disconnect", func(reason ...any) {
utils.Log().Info(`socket %s disconnected due to %s`, socket.Id(), reason[0])
})
})
func MakeSocket ¶
func MakeSocket() *Socket
func (*Socket) Broadcast ¶
func (s *Socket) Broadcast() *BroadcastOperator
Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
// the “foo” event will be broadcast to all connected clients, except this socket
socket.Broadcast().Emit("foo", "bar")
})
Return: a new BroadcastOperator instance for chaining
func (*Socket) Compress ¶
Sets the compress flag.
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
socket.Compress(false).Emit("hello")
})
Param: compress - if `true`, compresses the sending data
func (*Socket) Conn ¶
A reference to the underlying Client transport connection (Engine.IO Socket interface).
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
fmt.Println(socket.Conn().Transport().Name()) // prints "polling" or "websocket" or "webtransport"
socket.Conn().Once("upgrade", func(...any) {
fmt.Println(socket.Conn().Transport().Name()) // prints "websocket"
})
})
func (*Socket) Connected ¶
Whether the socket is currently connected or not.
io.Use(func(socket *socket.Socket, next func(*ExtendedError)) {
fmt.Println(socket.Connected()) // false
next(nil)
})
io.On("connection", func(args ...any) {
socket := args[0].(*socket.Socket)
fmt.Println(socket.Connected()) // true
})
func (*Socket) Disconnect ¶
Disconnects this client.
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
// disconnect this socket (the connection might be kept alive for other namespaces)
socket.Disconnect(false)
// disconnect this socket and close the underlying connection
socket.Disconnect(true)
})
Param: status - if `true`, closes the underlying connection
func (*Socket) Disconnected ¶
Whether the socket is currently disconnected
func (*Socket) Emit ¶
Emits to this client.
io.On("connection", func(args ...any) {
socket := args[0].(*socket.Socket)
socket.Emit("hello", "world")
// all serializable datastructures are supported (no need to call json.Marshal, But the map can only be of `map[string]any` type, currently does not support other types of maps)
socket.Emit("hello", 1, "2", map[string]any{"3": []string{"4"}, "5": types.NewBytesBuffer([]byte{6})})
// with an acknowledgement from the client
socket.Emit("hello", "world", func(args []any, err error) {
// ...
})
})
func (*Socket) EmitWithAck ¶
Emits an event and waits for an acknowledgement
io.On("connection", func(args ...any) => {
client := args[0].(*socket.Socket)
// without timeout
client.EmitWithAck("hello", "world")(func(args []any, err error) {
if err == nil {
fmt.Println(args) // one response per client
} else {
// some clients did not acknowledge the event in the given delay
}
})
// with a specific timeout
client.Timeout(1000 * time.Millisecond).EmitWithAck("hello", "world")(func(args []any, err error) {
if err == nil {
fmt.Println(args) // one response per client
} else {
// some clients did not acknowledge the event in the given delay
}
})
})
Return: a `func(socket.Ack)` that will be fulfilled when all clients have acknowledged the event
func (*Socket) Except ¶
func (s *Socket) Except(room ...Room) *BroadcastOperator
Except excludes a room when broadcasting. Returns a new BroadcastOperator for chaining.
func (*Socket) In ¶
func (s *Socket) In(room ...Room) *BroadcastOperator
In targets a room when broadcasting. Returns a new BroadcastOperator for chaining.
func (*Socket) ListenersAny ¶
func (s *Socket) ListenersAny() []types.EventListener
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() []types.EventListener
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) Local ¶
func (s *Socket) Local() *BroadcastOperator
Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
// the “foo” event will be broadcast to all connected clients on this node, except this socket
socket.Local().Emit("foo", "bar")
})
Return: a new BroadcastOperator instance for chaining
func (*Socket) NotifyOutgoingListeners ¶
func (*Socket) OffAny ¶
func (s *Socket) OffAny(listener types.EventListener) *Socket
OffAny removes a specific or all listeners for any event received.
func (*Socket) OffAnyOutgoing ¶
func (s *Socket) OffAnyOutgoing(listener types.EventListener) *Socket
OffAnyOutgoing removes a specific or all listeners for any event sent.
func (*Socket) OnAny ¶
func (s *Socket) OnAny(listener types.EventListener) *Socket
OnAny adds a listener that will be fired when any event is received.
func (*Socket) OnAnyOutgoing ¶
func (s *Socket) OnAnyOutgoing(listener types.EventListener) *Socket
OnAnyOutgoing adds a listener that will be fired when any event is sent.
func (*Socket) PrependAny ¶
func (s *Socket) PrependAny(listener types.EventListener) *Socket
PrependAny adds a listener to the beginning of the listeners array for any event received.
func (*Socket) PrependAnyOutgoing ¶
func (s *Socket) PrependAnyOutgoing(listener types.EventListener) *Socket
PrependAnyOutgoing adds a listener to the beginning of the listeners array for any event sent.
func (*Socket) Recovered ¶
Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will be transmitted to the client, the data attribute and the rooms will be restored.
func (*Socket) Request ¶
func (s *Socket) Request() *types.HttpContext
A reference to the request that originated the underlying Engine.IO Socket.
func (*Socket) Rooms ¶
Returns the rooms the socket is currently in.
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
fmt.Println(socket.Rooms()) // *types.Set { <socket.id> }
socket.Join("room1")
fmt.Println(socket.Rooms()) // *types.Set { <socket.id>, "room1" }
})
func (*Socket) Send ¶
Sends a `message` event.
This method mimics the WebSocket.send() method.
See: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
socket.Send("hello");
// this is equivalent to
socket.Emit("message", "hello");
});
func (*Socket) SetData ¶
Additional information that can be attached to the Socket instance and which will be used in the [Server.fetchSockets()] method.
func (*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 client:
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
socket.Timeout(1000 * time.Millisecond).Emit("my-event", func(args []any, err error) {
if err != nil {
// the client did not acknowledge the event in the given delay
}
})
})
func (*Socket) To ¶
func (s *Socket) To(room ...Room) *BroadcastOperator
To targets a room when broadcasting. Returns a new BroadcastOperator for chaining.
func (*Socket) Use ¶
func (s *Socket) Use(fn SocketMiddleware) *Socket
Use registers a middleware function for this socket.
func (*Socket) Volatile ¶
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).
io.On("connection", func(clients ...any) {
socket := clients[0].(*socket.Socket)
socket.Volatile().Emit("hello") // the client may or may not receive it
})
type SocketDetails ¶
type SocketId ¶
type SocketId string
A public ID, sent by the server at the beginning of the Socket.IO session and which can be used for private messaging
type SocketMiddleware ¶
type StrictEventEmitter ¶
type StrictEventEmitter struct {
types.EventEmitter
}
Strictly typed version of an `EventEmitter`. A `TypedEventEmitter` takes type parameters for mappings of event names to event data types, and strictly types method calls to the `EventEmitter` according to these event maps.
func NewStrictEventEmitter ¶
func NewStrictEventEmitter() *StrictEventEmitter
func (*StrictEventEmitter) Emit ¶
func (s *StrictEventEmitter) Emit(ev string, args ...any)
Emit emits an event with the specified name and arguments to all listeners.
func (*StrictEventEmitter) EmitReserved ¶
func (s *StrictEventEmitter) EmitReserved(ev string, args ...any)
EmitReserved emits a reserved event. Only subclasses should use this method.
func (*StrictEventEmitter) EmitUntyped ¶
func (s *StrictEventEmitter) EmitUntyped(ev string, args ...any)
EmitUntyped emits an event without strict type checking. Only subclasses should use this method.
func (*StrictEventEmitter) Listeners ¶
func (s *StrictEventEmitter) Listeners(ev string) []types.EventListener
Listeners returns a slice of listeners subscribed to the given event name.
func (*StrictEventEmitter) On ¶
func (s *StrictEventEmitter) On(ev string, listeners ...types.EventListener) error
On adds the listener function as an event listener for the given event name.
func (*StrictEventEmitter) Once ¶
func (s *StrictEventEmitter) Once(ev string, listeners ...types.EventListener) error
Once adds a one-time listener function for the given event name.
type TransportCtor ¶
type TransportCtor = transports.TransportCtor
var ( Polling TransportCtor = &PollingBuilder{} WebSocket TransportCtor = &WebSocketBuilder{} WebTransport TransportCtor = &WebTransportBuilder{} )
type WebSocketBuilder ¶
type WebSocketBuilder = transports.WebSocketBuilder
type WebTransportBuilder ¶
type WebTransportBuilder = transports.WebTransportBuilder