ws

package module
v0.0.0-...-0b26d44 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2023 License: MIT Imports: 10 Imported by: 0

README

ws

Go Reference

WebSocket wrapper with support for reconnecting on disconnect

Documentation

Index

Constants

View Source
const (
	DefaultReconnectionTimeout   = 30 * time.Second
	DefaultPingInterval          = 1 * time.Second
	DefaultPongInterval          = 5 * time.Second
	DefaultPingDeadline          = 10 * time.Second
	DefaultLinearBackoffDuration = 1 * time.Second
)

Default WebSocket client constants

Variables

View Source
var (
	ErrClientOptionReconnectionTimeoutInvalid = errors.New("ws: client option ReconnectionTimeout invalid")
	ErrClientOptionPingIntervalInvalid        = errors.New("ws: client option PingInterval invalid")
	ErrClientOptionPongIntervalInvalid        = errors.New("ws: client option PongInterval invalid")
	ErrClientOptionPingDeadlineInvalid        = errors.New("ws: client option PingDeadline invalid")
)

Errors for invalid client options

View Source
var (
	DefaultReconnectionBackoff = backoff.LinearBackoff(-1, DefaultLinearBackoffDuration)
)

Default WebSocket client variables

Functions

This section is empty.

Types

type Client

type Client struct {
	*websocket.Conn
	// contains filtered or unexported fields
}

WebSocket client

func Dial

func Dial(urlStr string, requestHeader http.Header) (*Client, *http.Response, error)

Dial creates a new client connection by calling DialContext with a background context

func DialContext

func DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Client, *http.Response, error)

DialContext creates a new client connection. Use requestHeader to specify the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). Use the response.Header to get the selected subprotocol (Sec-WebSocket-Protocol) and cookies (Set-Cookie).

The context will be used in the request and in the Dialer.

If the WebSocket handshake fails, ErrBadHandshake is returned along with a non-nil *http.Response so that callers can handle redirects, authentication, etcetera. The response body may not contain the entire response and does not need to be closed by the application.

func DialContextWithDialer

func DialContextWithDialer(
	ctx context.Context,
	dialer *websocket.Dialer,
	urlStr string,
	requestHeader http.Header,
) (*Client, *http.Response, error)

DialContextWithDialer

func DialContextWithOptions

func DialContextWithOptions(
	ctx context.Context,
	dialer *websocket.Dialer,
	urlStr string,
	requestHeader http.Header,
	opts *ClientOpts,
) (*Client, *http.Response, error)

DialContextWithOptions

func (*Client) Close

func (c *Client) Close() error

Close closes the underlying network connection without sending or waiting for a close message.

func (*Client) CloseHandler

func (c *Client) CloseHandler() func(code int, text string) error

CloseHandler returns the current close handler

func (*Client) Closed

func (c *Client) Closed() bool

Returns true if the connection is closed

func (*Client) Connected

func (c *Client) Connected() bool

Returns true if we are connected to the WebSocket conneection

func (*Client) Connection

func (c *Client) Connection() *websocket.Conn

Safely access the WebSocket connection

func (*Client) EnableWriteCompression

func (c *Client) EnableWriteCompression(enable bool)

EnableWriteCompression enables and disables write compression of subsequent text and binary messages. This function is a noop if compression was not negotiated with the peer.

func (*Client) LocalAddr

func (c *Client) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Client) NextReader

func (c *Client) NextReader() (messageType int, r io.Reader, err error)

NextReader returns the next data message received from the peer. The returned messageType is either TextMessage or BinaryMessage.

There can be at most one open reader on a connection. NextReader discards the previous message if the application has not already consumed it.

Applications must break out of the application's read loop when this method returns a non-nil error value. Errors returned from this method are permanent. Once this method returns a non-nil error, all subsequent calls to this method return the same error.

func (*Client) NextWriter

func (c *Client) NextWriter(messageType int) (io.WriteCloser, error)

NextWriter returns a writer for the next message to send. The writer's Close method flushes the complete message to the network.

There can be at most one open writer on a connection. NextWriter closes the previous writer if the application has not already done so.

All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and PongMessage) are supported.

func (*Client) PingHandler

func (c *Client) PingHandler() func(appData string) error

PingHandler returns the current ping handler

func (*Client) PongHandler

func (c *Client) PongHandler() func(appData string) error

PongHandler returns the current pong handler

func (*Client) ReadJSON

func (c *Client) ReadJSON(v interface{}) error

ReadJSON reads the next JSON-encoded message from the connection and stores it in the value pointed to by v.

See the documentation for the encoding/json Unmarshal function for details about the conversion of JSON to a Go value.

func (*Client) ReadMessage

func (c *Client) ReadMessage() (messageType int, p []byte, err error)

ReadMessage is a helper method for getting a reader using NextReader and reading from that reader to a buffer.

func (*Client) Reconnect

func (c *Client) Reconnect(ctx context.Context) <-chan bool

Reconnect to the WebSocket server

func (*Client) RemoteAddr

func (c *Client) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Client) SetCloseHandler

func (c *Client) SetCloseHandler(h func(code int, text string) error)

SetCloseHandler sets the handler for close messages received from the peer. The code argument to h is the received close code or CloseNoStatusReceived if the close message is empty. The default close handler sends a close message back to the peer.

The handler function is called from the NextReader, ReadMessage and message reader Read methods. The application must read the connection to process close messages as described in the section on Control Messages above.

The connection read methods return a CloseError when a close message is received. Most applications should handle close messages as part of their normal error handling. Applications should only set a close handler when the application must perform some action before sending a close message back to the peer.

func (*Client) SetCompressionLevel

func (c *Client) SetCompressionLevel(level int) error

SetCompressionLevel sets the flate compression level for subsequent text and binary messages. This function is a noop if compression was not negotiated with the peer. See the compress/flate package for a description of compression levels.

func (*Client) SetPingHandler

func (c *Client) SetPingHandler(h func(appData string) error)

SetPingHandler sets the handler for ping messages received from the peer. The appData argument to h is the PING message application data. The default ping handler sends a pong to the peer.

The handler function is called from the NextReader, ReadMessage and message reader Read methods. The application must read the connection to process ping messages as described in the section on Control Messages above.

func (*Client) SetPongHandler

func (c *Client) SetPongHandler(h func(appData string) error)

SetPongHandler sets the handler for pong messages received from the peer. The appData argument to h is the PONG message application data. The default pong handler does nothing.

The handler function is called from the NextReader, ReadMessage and message reader Read methods. The application must read the connection to process pong messages as described in the section on Control Messages above.

func (*Client) SetReadDeadline

func (c *Client) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline on the underlying network connection. After a read has timed out, the websocket connection state is corrupt and all future reads will return an error. A zero value for t means reads will not time out.

func (*Client) SetReadLimit

func (c *Client) SetReadLimit(limit int64)

SetReadLimit sets the maximum size in bytes for a message read from the peer. If a message exceeds the limit, the connection sends a close message to the peer and returns ErrReadLimit to the application.

func (*Client) SetWriteDeadline

func (c *Client) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline on the underlying network connection. After a write has timed out, the websocket state is corrupt and all future writes will return an error. A zero value for t means writes will not time out.

func (*Client) Subprotocol

func (c *Client) Subprotocol() string

Subprotocol returns the negotiated protocol for the connection.

func (*Client) UnderlyingConn

func (c *Client) UnderlyingConn() net.Conn

UnderlyingConn returns the internal net.Conn. This can be used to further modifications to connection specific flags.

func (*Client) WriteControl

func (c *Client) WriteControl(messageType int, data []byte, deadline time.Time) error

WriteControl writes a control message with the given deadline. The allowed message types are CloseMessage, PingMessage and PongMessage.

func (*Client) WriteJSON

func (c *Client) WriteJSON(v interface{}) error

WriteJSON writes the JSON encoding of v as a message.

See the documentation for encoding/json Marshal for details about the conversion of Go values to JSON.

func (*Client) WriteMessage

func (c *Client) WriteMessage(messageType int, data []byte) error

WriteMessage is a helper method for getting a writer using NextWriter, writing the message and closing the writer.

func (*Client) WritePreparedMessage

func (c *Client) WritePreparedMessage(pm *websocket.PreparedMessage) error

WritePreparedMessage writes prepared message into connection.

type ClientErrorHandler

type ClientErrorHandler func(c *Client, conn *websocket.Conn, err error)

Client error handler function type

type ClientOpts

type ClientOpts struct {
	ReconnectionTimeout        time.Duration
	ReconnectionBackoff        backoff.Backoff
	PingInterval               time.Duration
	PongInterval               time.Duration
	PingDeadline               time.Duration
	OnConnect                  ConnectionHandler
	OnDisconnect               ConnectionHandler
	OnReaderError              ClientErrorHandler
	OnReconnectFailure         ClientErrorHandler
	OnCloseError               ClientErrorHandler
	OnSetCompressionLevelError ClientErrorHandler
	OnSetReadDeadlineError     ClientErrorHandler
	OnSetWriteDeadlineError    ClientErrorHandler
}

WebSocket client options

func DefaultOpts

func DefaultOpts() *ClientOpts

Get the Default WebSocket client options

type ConnectionHandler

type ConnectionHandler func(c *Client, conn *websocket.Conn)

Handler to be called when there is a connection or disconnection

Jump to

Keyboard shortcuts

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