socket

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LeaveReasonLeave  = LeaveReason(0) // Client called _leave event (channel.leave()).
	LeaveReasonRejoin = LeaveReason(1) // Client called _join and there is already an active socket for the same topic
	LeaveReasonClose  = LeaveReason(2) // Connection lost and session is terminated. See Session.ScheduleShutdown
)
View Source
const (
	ReplyStatusCodeOk    = 0
	ReplyStatusCodeError = 1
	MessageTypePush      = MessageType(0)
	MessageTypeReply     = MessageType(1) // Defines a reply Message sent from channels to Transport.
	MessageTypeBroadcast = MessageType(2) // Defines a Message sent from pubsub to channels and vice-versa.
)
View Source
const (
	StatusJoining = Status(0)
	StatusJoined  = Status(1)
	StatusLeaving = Status(2)
	StatusRemoved = Status(3)
)

Variables

View Source
var (
	ErrJoinCrashed    = fmt.Errorf("join crashed")
	ErrUnmatchedTopic = fmt.Errorf("unmatched topic")
)
View Source
var (
	ErrSocketNotJoined = fmt.Errorf("socket not joined")
)

Functions

func ClientJsHandler

func ClientJsHandler(r *chain.Router, route string)

ClientJsHandler add "/chain.js" endpoint

Types

type Channel

type Channel struct {
	TopicPattern string // The string pattern, for example `"room:*"`, `"users:*"`, or `"system"`
	// contains filtered or unexported fields
}

Channel provide a means for bidirectional communication from clients that integrate with the pubsub layer for soft-realtime functionality.

func NewChannel

func NewChannel(topicPattern string, factory func(channel *Channel)) *Channel

NewChannel Defines a channel matching the given topic.

func (*Channel) Broadcast

func (c *Channel) Broadcast(topic string, event string, payload any) (err error)

Broadcast on the pubsub server with the given topic, event and payload.

func (*Channel) Dispatch

func (c *Channel) Dispatch(topic string, msg any, from string)

Dispatch Hook invoked by pubsub dispatch.

func (*Channel) HandleIn

func (c *Channel) HandleIn(event string, handler InHandler)

HandleIn Handle incoming `event`s.

## Example

	channel.HandleIn("current_rank", func(event string, payload any, socket *Socket) (reply any, err error) {
		// client asks for their current rank, push sent directly as a new event.
		socket.Push("current_rank", map[string]any{"val": game.GetRank(socket.Get("user"))})
		return
    })

func (*Channel) HandleOut

func (c *Channel) HandleOut(event string, handler OutHandler)

HandleOut Intercepts outgoing `event`s.

By default, broadcasted events are pushed directly to the client, but intercepting events gives your channel a chance to customize the event for the client to append extra information or filter the message from being delivered.

*Note*: intercepting events can introduce significantly more overhead if a large number of subscribers must customize a message since the broadcast will be encoded N times instead of a single shared encoding across all subscribers.

## Example

	channel.HandleOut("new_msg", func(event string, payload any, socket *Socket) {
		if obj, valid := payload.(map[string]any); valid {
			obj["is_editable"] = User.CanEditMessage(socket.Get("user"), obj)
       		socket.Push("new_msg", obj)
		}
	})

func (*Channel) Join

func (c *Channel) Join(topic string, handler JoinHandler)

Join Handle channel joins by `topic`.

To authorize a socket, return `nil, nil` or `SOME_REPLY_PAYLOAD, nil`.

To refuse authorization, return `nil, reason`.

Example

	channel.Join("room:lobby", func Join(payload any, socket *Socket) (reply any, err error)
    	if !authorized(payload) {
			err = errors.New("unauthorized")
       	}
		return
     })

func (*Channel) Leave

func (c *Channel) Leave(topic string, handler LeaveHandler)

Leave Invoked when the socket is about to leave a Channel. See LeaveHandler

func (*Channel) LocalBroadcast

func (c *Channel) LocalBroadcast(topic string, event string, payload any) (err error)

LocalBroadcast on the pubsub server with the given topic, event and payload.

type ConfigHandler

type ConfigHandler func(handler *Handler, router *chain.Router, endpoint string) error

type ConnectHandler

type ConnectHandler func(session *Session) error

type Handler

type Handler struct {
	Options    map[string]any   // Permite receber opções que estrão acessíveis
	Channels   []*Channel       // Channels in this socket
	Transports []Transport      // Configured Transports
	Serializer chain.Serializer // Serializer definido para o Transport
	OnConfig   ConfigHandler    // Called by Handler.Configure
	OnConnect  ConnectHandler   // Called when client try to connect on a Transport
	// contains filtered or unexported fields
}

Handler A socket implementation that multiplexes messages over channels.

Handler is used as a module for establishing and maintaining the socket state via the Session and Socket struct.

Once connected to a socket, incoming and outgoing events are routed to Channel. The incoming client data is routed to channels via transports. It is the responsibility of the Handler to tie Transport and Channel together.

func (*Handler) Configure

func (h *Handler) Configure(router *chain.Router, endpoint string)

func (*Handler) Connect

func (h *Handler) Connect(endpoint string, params map[string]string) (session *Session, err error)

Connect invoked by Transport, initializes a new session

func (*Handler) Dispatch

func (h *Handler) Dispatch(payload []byte, session *Session)

Dispatch Processes messages from Transport (client)

func (*Handler) Resume

func (h *Handler) Resume(socketId string) *Session

Resume used by Transport, tries to recover the session if it still alive

type InHandler

type InHandler func(event string, payload any, socket *Socket) (reply any, err error)

InHandler invoked when the client push an event to a channel (`js: channel.push(event, payload)`).

See Channel.HandleIn

type JoinHandler

type JoinHandler func(payload any, socket *Socket) (reply any, err error)

JoinHandler invoked when the client joins a channel (event:_join, `js: channel.join()`).

See Channel.Join

type LeaveHandler

type LeaveHandler func(socket *Socket, reason LeaveReason)

LeaveHandler invoked when the socket leave a channel.

See LeaveReason, Channel.Leave

type LeaveReason

type LeaveReason int

LeaveReason reasons why a LeaveHandler is invoked

type Message

type Message struct {
	Kind    MessageType `json:"k,omitempty"` // Type of message
	JoinRef int         `json:"j,omitempty"` // The unique number ref when joining
	Ref     int         `json:"r,omitempty"` // The unique number ref
	Status  int         `json:"s,omitempty"` // The reply status
	Topic   string      `json:"t,omitempty"` // The string topic or topic:subtopic pair namespace, for example "messages", "messages:123"
	Event   string      `json:"e,omitempty"` // The string event name, for example "_join"
	Payload any         `json:"p,omitempty"` // The Message payload
}

Message Defines a message dispatched over transport to channels and vice-versa.

type MessageSerializer

type MessageSerializer struct{}

func (*MessageSerializer) Decode

func (s *MessageSerializer) Decode(data []byte, v any) (out any, err error)

func (*MessageSerializer) Encode

func (s *MessageSerializer) Encode(v any) (data []byte, err error)

type MessageType

type MessageType int

type OutHandler

type OutHandler func(event string, payload any, socket *Socket)

OutHandler invoked when a broadcast message is intercepted.

See Channel.HandleOut

type Session

type Session struct {
	Params  map[string]string // Initialization parameters, received at connection time
	Options map[string]any    // Reference to Handler.Options
	// contains filtered or unexported fields
}

Session used by Transport, communication interface between Transport and Channel.

Keeps an active session on the server. Transport should invoke ScheduleShutdown method when user connection drops

func (*Session) Dispatch

func (s *Session) Dispatch(message []byte)

Dispatch message to Channel

func (*Session) Endpoint

func (s *Session) Endpoint() string

Endpoint Path to socket endpoint

func (*Session) GetSocket

func (s *Session) GetSocket(topic string) *Socket

GetSocket get the Socket associated with the given topic

func (*Session) Push

func (s *Session) Push(bytes []byte)

Push message to client

func (*Session) ScheduleShutdown

func (s *Session) ScheduleShutdown(after time.Duration)

ScheduleShutdown schedules the termination of this session on the server. In case of a user reconnection, invoke the StopScheduledShutdown or Handler.Resume methods

func (*Session) SocketId

func (s *Session) SocketId() string

SocketId Session id

func (*Session) StopScheduledShutdown

func (s *Session) StopScheduledShutdown()

StopScheduledShutdown cancels the final termination of that session.

Invoked by the Handler.Resume method

type Socket

type Socket struct {
	Params map[string]string // Initialization parameters, received at connection time.
	// contains filtered or unexported fields
}

Socket Channel integration.

Allows the channel to manage socket state data through the Socket.Set and Socket.Get

func (*Socket) Broadcast

func (s *Socket) Broadcast(event string, payload any) (err error)

Broadcast an event to all subscribers of the socket topic.

func (*Socket) Endpoint

func (s *Socket) Endpoint() string

func (*Socket) Get

func (s *Socket) Get(key string) (value any)

Get a value from Socket (server side only)

func (*Socket) Id

func (s *Socket) Id() string

func (*Socket) Push

func (s *Socket) Push(event string, payload any) (err error)

Push message to client

func (*Socket) Send

func (s *Socket) Send(bytes []byte) error

Send encoded message to client

func (*Socket) Session

func (s *Socket) Session() *Session

func (*Socket) Set

func (s *Socket) Set(key string, value any)

Set a value on Socket (server side only)

func (*Socket) Status

func (s *Socket) Status() Status

func (*Socket) Topic

func (s *Socket) Topic() string

type Status

type Status int

type Transport

type Transport interface {
	Configure(h *Handler, r *chain.Router, endpoint string)
}

type TransportSSE

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

func (*TransportSSE) Configure

func (t *TransportSSE) Configure(handler *Handler, router *chain.Router, endpoint string)

Jump to

Keyboard shortcuts

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