A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.
package wsclient
import "github.com/nsgo-dev/game/pkg/online/wsclient"Visão geral
Package wsclient provides a plain RFC 6455 WebSocket client for talking to servers that are not a netplay WebSocketServer: third-party game backends such as Nakama or Colyseus, chat integrations, hosted realtime services, or a custom JSON protocol shared with a web dashboard. It offers the same API on native targets and in the browser (js/wasm), built on the shared framing of pkg/online/internal/wsproto.
To talk to a server written with this repository's netplay package, use netplay.DialWebSocket instead: it speaks netplay's own handshake and channel framing on top of WebSocket, which a plain client does not.
Índice
- Constantes
- Variáveis
- type Client
- func Dial(ctx context.Context, rawURL string, opts Options) (*Client, error)
- func (c *Client) Buffered() int
- func (c *Client) Close(code int, reason string) error
- func (c *Client) CloseStatus() (code int, reason string)
- func (c *Client) Dropped() int
- func (c *Client) Err() error
- func (c *Client) Protocol() string
- func (c *Client) Recv() (msg Message, ok bool)
- func (c *Client) Send(payload []byte) error
- func (c *Client) SendText(text string) error
- func (c *Client) State() State
- type Message
- type Options
- type State
Constantes
const (
CloseNormal = 1000 // the purpose of the connection is fulfilled
CloseGoingAway = 1001 // server going down, or the page is navigating away
CloseProtocolError = 1002 // the peer broke the protocol
CloseUnsupported = 1003 // the peer sent a data type it does not accept
CloseNoStatus = 1005 // reserved: the close frame carried no code
CloseAbnormal = 1006 // reserved: the connection dropped with no close frame at all
CloseMessageTooBig = 1009 // the peer sent a message too big to process
)RFC 6455 §7.4 close status codes a game most often sends or reads from CloseStatus.
const (
// DefaultMaxMessage bounds a received or sent message when Options.MaxMessage is zero.
DefaultMaxMessage = 4 << 20 // 4 MiB, as in netplay
// DefaultMaxInbox bounds the messages queued for Recv when Options.MaxInbox is zero.
DefaultMaxInbox = 256
)Variáveis
var (
// ErrClosed is returned when operating on a closed client.
ErrClosed = errors.New("net: websocket client closed")
// ErrMessageTooLarge is returned by Send and SendText for a payload over Options.MaxMessage, and reported by Err when an incoming message passes it.
ErrMessageTooLarge = errors.New("net: websocket message too large")
// ErrProtocol is reported by Err when the server broke RFC 6455, such as starting a new message before finishing a fragmented one.
ErrProtocol = errors.New("net: websocket protocol error")
// ErrHeadersUnsupported is returned by Dial in the browser when Options.Header is non-empty: the browser WebSocket API cannot set handshake headers.
ErrHeadersUnsupported = errors.New("net: websocket handshake headers are not supported in the browser")
// ErrInvalidCloseCode is returned by Close for a code outside the ranges RFC 6455 §7.4 allows an endpoint to send.
ErrInvalidCloseCode = errors.New("net: invalid websocket close code")
)Tipos
type Client struct {
// contains filtered or unexported fields
}Client is a plain RFC 6455 WebSocket client connected to any ws:// or wss:// server. Dial returns it open; the read side runs on its own goroutine, so Recv, State and Close are safe to call from the game loop while Send and SendText are safe from any goroutine.
func Dial(ctx context.Context, rawURL string, opts Options) (*Client, error)Dial opens a WebSocket connection to rawURL (ws:// or wss://) and returns the client once the server's upgrade response arrives, or an error when the dial, TLS or handshake fails. ctx bounds the dial and the handshake; after that the connection has no idle timeout, because a third-party server may stay silent for as long as it likes. The client answers the server's pings with pongs on its own.
func (c *Client) Buffered() intBuffered returns the number of received messages waiting for Recv.
func (c *Client) Close(code int, reason string) errorClose sends a close frame with code and reason and closes the connection. A zero code sends no status code, and CloseStatus then reports CloseNoStatus. It is a no-op on an already closed client.
func (c *Client) CloseStatus() (code int, reason string)CloseStatus returns the status code and reason of the close that ended the connection: the peer's when it closed first, otherwise the ones Close was called with. The code is CloseNoStatus when the close frame carried none, CloseAbnormal when the connection dropped with no close frame at all, and 0 while the connection is still open.
func (c *Client) Dropped() intDropped returns how many received messages were dropped because the inbox was at its Options.MaxInbox bound.
func (c *Client) Err() errorErr returns why the connection closed: nil for a clean close, ErrMessageTooLarge or ErrProtocol for one the client ended, or the read error for a dropped connection.
func (c *Client) Protocol() stringProtocol returns the subprotocol the server selected at the handshake, or "" for none.
func (c *Client) Recv() (msg Message, ok bool)Recv pops the oldest received message without blocking, reporting ok false when the inbox is empty.
func (c *Client) Send(payload []byte) errorSend queues payload as one binary message. It returns ErrClosed once the connection is closed and ErrMessageTooLarge for a payload over Options.MaxMessage.
func (c *Client) SendText(text string) errorSendText queues text as one UTF-8 text message, with the same errors as Send.
func (c *Client) State() StateState returns whether the connection is Open or Closed.
type Message struct {
Text bool
Data []byte
}Message is one WebSocket message received from the server. Text reports whether it arrived as a text frame; Data holds its payload either way.
type Options struct {
// Protocols lists the subprotocols the client offers, in preference order; the server picks one, which Protocol reports, or none. Browsers support subprotocols on every target.
Protocols []string
// Header carries extra handshake request headers, such as an Authorization token. It is native only: the browser WebSocket API cannot set headers, so a browser Dial with a non-empty Header fails with ErrHeadersUnsupported instead of silently dropping them. Entries naming a header the handshake writes itself (Host, Upgrade, Connection, Sec-WebSocket-*) are ignored.
Header http.Header
// MaxMessage is the largest message, in bytes, the client receives or sends. Zero uses DefaultMaxMessage. A larger incoming message is refused: the connection closes and Err reports ErrMessageTooLarge.
MaxMessage int
// MaxInbox is the most received messages the client queues for Recv. Zero uses DefaultMaxInbox; a negative value removes the bound. Past the bound the oldest queued message is dropped to make room, and Dropped counts the loss.
MaxInbox int
}Options tunes Dial. The zero value is a plain connection with default limits.
type State intState reports where a Client is in its lifecycle. A client is Open once Dial returns it and moves to Closed when either side closes the connection or the connection drops; a plain client does not reconnect, so a Closed client is done and a new one takes its place.
const (
// Open means the connection is up and Send, SendText and Recv operate on it.
Open State = iota
// Closed means the connection ended, cleanly or not; CloseStatus and Err report how.
Closed
)