ws

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ws provides message I/O over already-upgraded WebSocket connections.

A Conn wraps a net.Conn and forwards its deadlines and addresses; closing the transport stays with the caller, and NetConn hands the whole thing back as a net.Conn view. The handshake is elsewhere: ws takes the negotiated result through Config.

Reading

One goroutine reads at a time. Serve runs the usual loop, handing each message to a MessageHandler. ReadMessage returns whole messages, borrowed until the next read call. NextMessage then Read delivers a message in chunks as its frames arrive, with io.EOF at the end, and WriteTo relays the rest of a message to an io.Writer frame by frame. Compressed messages inflate as they stream through Read and WriteTo, holding one frame and the inflater's window, and whole through ReadMessage.

Control frames are dispatched on the way through the ControlHandler, whose default answers pings and echoes close codes. A protocol failure sends its close code once and fails every later read with the same *Error; the peer's close arrives as *CloseError.

Writing

Writes may come from any goroutine. Write sends one frame; BeginMessage, WriteChunk and EndMessage send a message of unknown length as fragments, and WriteFrom does that for an io.Reader. On a kernel socket a frame leaves as one writev of header and payload with no copy; elsewhere small frames are coalesced into one write. Outgoing text is never validated: the sender knows its data.

A Queue sends asynchronously through a goroutine that runs only while the queue is nonempty and coalesces everything accumulated into one write; once a connection has a queue its synchronous writes join it in order. Prepared encodes a message once for many recipients.

Borrowing

Payloads from ReadMessage, chunks from Read, and the bytes of a Prepared are valid until the next call on the object that produced them and are then reused. Nothing enforces this and the failure is silent corruption: copy before keeping a payload past the next read or handing it to another goroutine.

Memory

An idle connection holds its read buffer, 4 KiB by default, and nothing else; message buffers, compressors and decompressors come from pools and go back after use.

A Queue holds at most its limit of unwritten bytes, a high-water mark that fails Send with ErrQueueFull rather than blocking, so a server's bound is connections times limit. A synchronous Write instead blocks on the full socket and leaves the backlog in kernel buffers.

With send context takeover a compressor attached to the connection continues one stream at about 800 KB per connection. CompressionShared borrows a pooled one per message and primes it from the 32 KB window instead, which costs CPU per message and wins once many connections with large messages compete for cache.

Index

Examples

Constants

View Source
const (
	DefaultReadBufferSize = 4 << 10
	DefaultMaxMessageSize = 8 << 20
	DefaultFragmentSize   = 64 << 10
	// DefaultMinSize is the payload size below which messages go uncompressed
	// when Compression.MinSize is zero: flate encoders emit literals only for
	// smaller flushed blocks, so compressing them costs CPU and adds bytes.
	DefaultMinSize = 128
)

Defaults for the zero values of the corresponding Config fields.

View Source
const NoStatus = 1005

NoStatus is the close code reported when the peer sent none.

Variables

View Source
var (
	// ErrClosing means a close frame has already been sent.
	ErrClosing = errors.New("ews/ws: close frame already sent")
	// ErrProtocol means the peer violated the framing or message rules.
	ErrProtocol = errors.New("ews/ws: invalid frame or message sequence")
	// ErrInvalidUTF8 means a text message or close reason is not valid UTF-8.
	ErrInvalidUTF8 = errors.New("ews/ws: invalid UTF-8")
	// ErrMessageTooLarge means a message exceeds Config.MaxMessageSize.
	ErrMessageTooLarge = errors.New("ews/ws: message exceeds limit")
	// ErrInvalidData means a compressed message could not be decompressed.
	ErrInvalidData = errors.New("ews/ws: invalid compressed message data")
	// ErrInvalidConfig means NewConn received an invalid Config.
	ErrInvalidConfig = errors.New("ews/ws: invalid configuration")
	// ErrMessageOpen means a fragmented message is in progress, so Write and
	// BeginMessage must wait for EndMessage.
	ErrMessageOpen = errors.New("ews/ws: fragmented message in progress")
	// ErrNoMessage means WriteChunk or EndMessage was called without BeginMessage.
	ErrNoMessage = errors.New("ews/ws: no fragmented message in progress")
	// ErrQueueFull means a Queue has reached its byte limit.
	ErrQueueFull = errors.New("ews/ws: send queue full")
)
View Source
var ErrUnexpectedType = errors.New("ews/ws: message of unexpected type")

ErrUnexpectedType means a NetConn received a message of the other data type.

Functions

func NetConn

func NetConn(c *Conn, op codec.Opcode) net.Conn

NetConn presents a connection as a net.Conn for tunneling other protocols over WebSocket. Each Write sends one message of the given type, Text or Binary. Read delivers message payloads in order, continuing into the next message as one ends and never spanning a message in a single call.

A message of the other type closes the connection with code 1003 and fails every later Read with ErrUnexpectedType. A peer close with code 1000 or 1001 reads as io.EOF; any other close code is returned as the CloseError.

Deadlines and addresses are the transport's, so a read deadline interrupts a blocked Read and leaves the connection usable, while a write deadline that expires mid-frame ends it, as it would any framed protocol. Close sends a normal close frame and closes the transport.

Reads are serialized; writes may come from any goroutine, as on Conn.

Example
package main

import (
	"fmt"
	"io"
	"net"

	"github.com/33TU/ews/codec"
	"github.com/33TU/ews/ws"
)

// examplePair connects a server and a client over an in-memory pipe. Real
// programs get the transport from ews.Upgrade, ews.Server or ews.Dial.
func examplePair() (server, client *ws.Conn) {
	sc, cc := net.Pipe()
	server, _ = ws.NewConn(sc, ws.Config{Role: ws.Server})
	client, _ = ws.NewConn(cc, ws.Config{Role: ws.Client})
	return server, client
}

func main() {
	server, client := examplePair()
	sc, cc := ws.NetConn(server, codec.Binary), ws.NetConn(client, codec.Binary)
	go func() {
		// Each Write is one message; the reader sees a byte stream.
		io.WriteString(cc, "tunneled ")
		io.WriteString(cc, "bytes")
		cc.Close()
	}()
	all, err := io.ReadAll(sc)
	fmt.Println(string(all), err)
}
Output:
tunneled bytes <nil>

func Serve added in v0.2.0

func Serve(c *Conn, h MessageHandler) error

Serve reads messages from c and hands each to h until a read fails or h returns an error, and returns that error: a *CloseError when the peer closed, a *Error after a protocol failure, the transport's error otherwise. It is the read loop most servers write by hand, on the caller's goroutine; control frames still go through c's ControlHandler on the way.

Types

type CloseError

type CloseError struct {
	Code   uint16
	Reason string
}

CloseError is returned by reads after the peer's close frame has been handled. Code is NoStatus when the frame carried no status code.

func (*CloseError) Error

func (e *CloseError) Error() string

type Config

type Config struct {
	Role Role
	// ReadBufferSize is the transport read size. Zero uses DefaultReadBufferSize.
	ReadBufferSize int
	// MaxMessageSize bounds ReadMessage. Zero uses DefaultMaxMessageSize.
	MaxMessageSize int
	// FragmentSize is the chunk WriteFrom reads and sends per frame, and so
	// the largest content it sends as a single frame. Larger fragments mean
	// fewer frames and syscalls; two buffers of this size are in flight per
	// call. Zero uses DefaultFragmentSize.
	FragmentSize int
	// ValidateUTF8 makes ReadMessage check that text messages are valid
	// UTF-8 and fail the connection with close code 1007 when they are not,
	// as RFC 6455 requires. Off by default: it costs one pass over each text
	// message, and applications that decode text themselves catch invalid
	// input anyway. Read delivers chunks unvalidated either way, and outgoing
	// text is never checked: the sender knows its own data.
	ValidateUTF8 bool
	// Compression holds negotiated permessage-deflate parameters, or nil.
	Compression *handshake.Compression
	// CompressionShared borrows a compressor from the shared pool for every
	// compressed write instead of keeping one attached to the connection.
	// Without send context takeover compressors are always shared.
	//
	// With send context takeover an attached compressor continues one
	// stream and is the fastest per message, but holds about 800 KB per
	// connection; a shared one is primed from the 32 KB window on each
	// message and costs more CPU per message but almost no memory, which
	// wins once thousands of connections compete for cache.
	CompressionShared bool
	// ControlHandler replaces the defaults. Nil uses DefaultControlHandler.
	ControlHandler ControlHandler
	// UserData is the initial value of Conn.UserData, for state a caller has
	// before the connection exists.
	UserData any
}

Config describes the local endpoint and negotiated parameters.

type Conn

type Conn struct {
	// ControlHandler overrides default control handling. Set before reading.
	ControlHandler ControlHandler

	// UserData holds application state. Concurrent access is the caller's responsibility.
	UserData any
	// contains filtered or unexported fields
}

Conn is a WebSocket connection over an upgraded transport. One goroutine may read at a time; writes may come from any goroutine.

func NewConn

func NewConn(conn net.Conn, cfg Config) (*Conn, error)

NewConn wraps an upgraded transport. Deadlines and addresses are the transport's, reachable through the Conn; closing it stays with the caller, since Close on a Conn sends the close frame.

func (*Conn) BeginMessage

func (c *Conn) BeginMessage(op codec.Opcode) error

BeginMessage starts a fragmented text or binary message. Each WriteChunk then sends one fragment and EndMessage finishes it. Until then Write and BeginMessage return ErrMessageOpen; Ping, Pong, and Close may interleave, as the protocol allows.

The message is compressed whenever compression is negotiated, regardless of MinSize.

func (*Conn) Close

func (c *Conn) Close(code uint16, reason string) error

Close sends a close frame once. Code zero sends an empty payload and requires an empty reason. Later data writes return ErrClosing. The transport stays open; reads deliver the peer's close as a *CloseError.

On a connection with a Queue the frame joins the queue behind the data already sent, so nothing queued is lost or follows the close, and Close returns once it is written.

func (*Conn) CloseSent

func (c *Conn) CloseSent() bool

CloseSent reports whether a close frame has been sent or attempted.

func (*Conn) EndMessage

func (c *Conn) EndMessage() error

EndMessage sends the final, empty fragment of the open message.

func (*Conn) LocalAddr added in v0.3.0

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

LocalAddr returns the transport's local address.

func (*Conn) NewQueue

func (c *Conn) NewQueue(limit int) *Queue

NewQueue attaches a queue to c, or returns the one it already has.

limit is a high-water mark on bytes queued by Send and SendPrepared: an empty queue accepts any message, and a message that would push a nonempty queue past the limit is refused with ErrQueueFull rather than blocking, so a slow peer cannot stall the sender. The application decides what a full queue means, usually closing the connection.

Zero means 1 MiB on a new queue and leaves an existing queue's limit alone, so a hub can look a connection's queue up again with NewQueue(0); a nonzero limit on an existing queue adjusts it, taking effect on the next Send.

func (*Conn) NextMessage

func (c *Conn) NextMessage() (codec.Opcode, error)

NextMessage returns the opcode of the next text or binary message, dispatching control frames on the way. Any unread payload of the current message is discarded first.

func (*Conn) Ping

func (c *Conn) Ping(payload []byte) error

Ping sends a ping with at most 125 payload bytes.

func (*Conn) Pong

func (c *Conn) Pong(payload []byte) error

Pong sends a pong with at most 125 payload bytes. Pongs are allowed after Close.

func (*Conn) Read

func (c *Conn) Read(b []byte) (int, error)

Read copies payload of the current message into b, spanning continuation frames and dispatching interleaved control frames. It returns 0, io.EOF at the end of the message and before NextMessage has been called. Transport EOF mid-message is io.ErrUnexpectedEOF.

Text read in chunks is never UTF-8 validated; only complete messages are. Compressed messages are inflated as they stream, holding one frame at a time; a transport error during one ends the connection, since the inflater cannot resume.

Example
package main

import (
	"bytes"
	"fmt"
	"io"
	"net"

	"github.com/33TU/ews/codec"
	"github.com/33TU/ews/ws"
)

// examplePair connects a server and a client over an in-memory pipe. Real
// programs get the transport from ews.Upgrade, ews.Server or ews.Dial.
func examplePair() (server, client *ws.Conn) {
	sc, cc := net.Pipe()
	server, _ = ws.NewConn(sc, ws.Config{Role: ws.Server})
	client, _ = ws.NewConn(cc, ws.Config{Role: ws.Client})
	return server, client
}

func main() {
	server, client := examplePair()
	go client.Write(codec.Binary, bytes.Repeat([]byte("x"), 10))

	// A message read in chunks: NextMessage, then Read until io.EOF.
	if _, err := server.NextMessage(); err != nil {
		panic(err)
	}
	buf := make([]byte, 4)
	for {
		n, err := server.Read(buf)
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		fmt.Print(n, " ")
	}
	fmt.Println()
}
Output:
4 4 2

func (*Conn) ReadMessage

func (c *Conn) ReadMessage() (codec.Opcode, []byte, error)

ReadMessage returns the next complete text or binary message. The payload is borrowed until the next read call.

Messages larger than Config.MaxMessageSize, before or after decompression, fail with close code 1009; undecodable compressed data, and with Config.ValidateUTF8 text that is not valid UTF-8, fail with 1007.

Example
package main

import (
	"fmt"
	"net"

	"github.com/33TU/ews/codec"
	"github.com/33TU/ews/ws"
)

// examplePair connects a server and a client over an in-memory pipe. Real
// programs get the transport from ews.Upgrade, ews.Server or ews.Dial.
func examplePair() (server, client *ws.Conn) {
	sc, cc := net.Pipe()
	server, _ = ws.NewConn(sc, ws.Config{Role: ws.Server})
	client, _ = ws.NewConn(cc, ws.Config{Role: ws.Client})
	return server, client
}

func main() {
	server, client := examplePair()
	go client.Write(codec.Text, []byte("hello"))

	// The payload is borrowed: it is valid until the next read call.
	op, payload, err := server.ReadMessage()
	if err != nil {
		panic(err)
	}
	fmt.Println(op == codec.Text, string(payload))
}
Output:
true hello

func (*Conn) RemoteAddr added in v0.3.0

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

RemoteAddr returns the transport's remote address.

func (*Conn) SetDeadline added in v0.3.0

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the transport's read and write deadlines.

func (*Conn) SetReadDeadline added in v0.3.0

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

SetReadDeadline sets the transport's read deadline. An expired read deadline interrupts the blocked read with a timeout error and leaves the connection usable, so it serves as an idle timeout that a handler refreshes.

func (*Conn) SetWriteDeadline added in v0.3.0

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

SetWriteDeadline sets the transport's write deadline. A deadline that expires mid-frame ends the connection, as it would any framed protocol; with a Queue, the writer goroutine is what it interrupts.

func (*Conn) Transport added in v0.3.0

func (c *Conn) Transport() net.Conn

Transport returns the connection NewConn was given, for closing it or anything else the Conn does not forward.

func (*Conn) Write

func (c *Conn) Write(op codec.Opcode, payload []byte) error

Write sends one text or binary message as a single frame, compressed when negotiated and at least Compression.MinSize bytes long. payload is not retained after Write returns.

func (*Conn) WriteChunk

func (c *Conn) WriteChunk(payload []byte) error

WriteChunk sends one non-final fragment of the open message. Chunks are delivered to the peer as they are written; an empty chunk sends an empty frame.

func (*Conn) WriteFrom

func (c *Conn) WriteFrom(op codec.Opcode, r io.Reader) (int64, error)

WriteFrom sends r's content as one message and returns the bytes sent. Content that fits one Config.FragmentSize read goes out as a single frame; longer content is fragmented as it is read, one chunk ahead so the last chunk carries the FIN and nothing is held in memory beyond two chunks. A read error is returned with the message still open and the chunk being read unsent, since a fragmented message cannot be withdrawn; close the connection in that case.

Example
package main

import (
	"fmt"
	"net"
	"strings"

	"github.com/33TU/ews/codec"
	"github.com/33TU/ews/ws"
)

// examplePair connects a server and a client over an in-memory pipe. Real
// programs get the transport from ews.Upgrade, ews.Server or ews.Dial.
func examplePair() (server, client *ws.Conn) {
	sc, cc := net.Pipe()
	server, _ = ws.NewConn(sc, ws.Config{Role: ws.Server})
	client, _ = ws.NewConn(cc, ws.Config{Role: ws.Client})
	return server, client
}

func main() {
	server, client := examplePair()
	go func() {
		// Send content of unknown length as one message, fragmented as read.
		client.WriteFrom(codec.Text, strings.NewReader("streamed from a reader"))
	}()
	_, payload, err := server.ReadMessage()
	fmt.Println(string(payload), err)
}
Output:
streamed from a reader <nil>

func (*Conn) WritePrepared

func (c *Conn) WritePrepared(p *Prepared) error

WritePrepared sends a prepared message. On a server it writes the shared bytes with no encoding or copying; a client must mask, so it falls back to Write. A compressed variant advances the send window like any compressed message.

On a connection with a Queue the message joins the queue in order and WritePrepared returns once it has been written.

func (*Conn) WriteTo

func (c *Conn) WriteTo(w io.Writer) (int64, error)

WriteTo writes the rest of the current message to w, so io.Copy(w, c) moves a message without a buffer of its own. It returns nil at the end of the message and writes nothing when no message is open. An error from w is returned as is and leaves the rest of the message unread; NextMessage discards it.

Plain frames go to w as they arrive: what the read buffer holds is borrowed, and a longer remainder is read from the transport into the pooled message buffer in pieces of up to Config.FragmentSize. A compressed message is inflated as it streams into the message buffer, FragmentSize at a time, and each piece written.

Example
package main

import (
	"fmt"
	"io"
	"net"
	"strings"

	"github.com/33TU/ews/codec"
	"github.com/33TU/ews/ws"
)

// examplePair connects a server and a client over an in-memory pipe. Real
// programs get the transport from ews.Upgrade, ews.Server or ews.Dial.
func examplePair() (server, client *ws.Conn) {
	sc, cc := net.Pipe()
	server, _ = ws.NewConn(sc, ws.Config{Role: ws.Server})
	client, _ = ws.NewConn(cc, ws.Config{Role: ws.Client})
	return server, client
}

func main() {
	server, client := examplePair()
	go client.Write(codec.Text, []byte("copied without a buffer"))

	if _, err := server.NextMessage(); err != nil {
		panic(err)
	}
	var sb strings.Builder
	n, err := io.Copy(&sb, server) // Uses WriteTo through io.WriterTo.
	fmt.Println(n, err, sb.String())
}
Output:
23 <nil> copied without a buffer

type ControlHandler

type ControlHandler interface {
	OnPing(c *Conn, payload []byte) error
	OnPong(c *Conn, payload []byte) error
	OnClose(c *Conn, code uint16, reason []byte) error
}

ControlHandler handles control frames during reads. Payloads are borrowed for the duration of each call, and a shared handler must support concurrent calls from different connections.

Handlers replace the defaults: OnPing must send a Pong, and OnClose a close response if needed. They may write to c but must not read from it. An error terminates the connection.

type DefaultControlHandler

type DefaultControlHandler struct{}

DefaultControlHandler answers pings, ignores pongs, and echoes close codes. Embed it to override a single method.

func (DefaultControlHandler) OnClose

func (DefaultControlHandler) OnClose(c *Conn, code uint16, _ []byte) error

OnClose echoes the peer's close code. A failed echo is not an error: the peer has closed and may already have dropped the transport, and the read that dispatched this frame returns the peer's code, which is what the caller needs. Callers who care about the echo itself send their own.

func (DefaultControlHandler) OnPing

func (DefaultControlHandler) OnPing(c *Conn, payload []byte) error

OnPing answers with a pong carrying the same payload.

func (DefaultControlHandler) OnPong

func (DefaultControlHandler) OnPong(*Conn, []byte) error

OnPong ignores the frame.

type Error

type Error struct {
	Code uint16
	Err  error
}

Error is a terminal protocol failure and the close code that describes it. A close frame carrying Code has been sent when possible. Every later read returns the same error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type MessageFunc added in v0.2.0

type MessageFunc func(c *Conn, op codec.Opcode, payload []byte) error

MessageFunc adapts a function to MessageHandler.

func (MessageFunc) OnMessage added in v0.2.0

func (f MessageFunc) OnMessage(c *Conn, op codec.Opcode, payload []byte) error

OnMessage calls f.

type MessageHandler added in v0.2.0

type MessageHandler interface {
	// OnMessage is called on the goroutine running Serve with each complete
	// text or binary message. payload is borrowed until it returns; copy it
	// to keep it. It may write to c. Returning an error stops Serve, which
	// returns that error.
	OnMessage(c *Conn, op codec.Opcode, payload []byte) error
}

MessageHandler receives the data messages of one connection.

type Prepared

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

Prepared is a message encoded once for sending to many connections. Server frames carry no mask, so one encoding serves every recipient; a compressed variant is built on first use per compression configuration. A Prepared is immutable once made, safe for concurrent use, and garbage collected like any value: queues and connections that still refer to it keep it alive.

func Prepare

func Prepare(op codec.Opcode, payload []byte) (*Prepared, error)

Prepare encodes a text or binary message for WritePrepared. payload is copied.

Example
package main

import (
	"fmt"
	"net"

	"github.com/33TU/ews/codec"
	"github.com/33TU/ews/ws"
)

// examplePair connects a server and a client over an in-memory pipe. Real
// programs get the transport from ews.Upgrade, ews.Server or ews.Dial.
func examplePair() (server, client *ws.Conn) {
	sc, cc := net.Pipe()
	server, _ = ws.NewConn(sc, ws.Config{Role: ws.Server})
	client, _ = ws.NewConn(cc, ws.Config{Role: ws.Client})
	return server, client
}

func main() {
	server, client := examplePair()
	got := make(chan string)
	go func() {
		_, p, _ := client.ReadMessage()
		got <- string(p)
	}()

	// Encode once, send to every recipient by reference.
	p, err := ws.Prepare(codec.Text, []byte("to everyone"))
	if err != nil {
		panic(err)
	}
	q := server.NewQueue(0)
	q.SendPrepared(p)
	fmt.Println(<-got)
}
Output:
to everyone

func PrepareAppend added in v0.2.2

func PrepareAppend(op codec.Opcode, size int, fill func(dst []byte) ([]byte, error)) (*Prepared, error)

PrepareAppend is Prepare for an encoder that appends: fill appends the payload to dst and returns the result, so a protobuf MarshalAppend or a JSON append marshals straight into the frame, one allocation and no copy. size is a capacity hint for the payload, such as proto.Size; with zero the frame grows as the encoder appends. A fill error is returned as is.

func (*Prepared) Opcode

func (p *Prepared) Opcode() codec.Opcode

Opcode returns the message type.

func (*Prepared) Payload

func (p *Prepared) Payload() []byte

Payload borrows the message payload.

type Queue

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

Queue sends messages asynchronously: Send encodes a message and returns without touching the transport, and a goroutine that runs only while the queue is nonempty writes what has accumulated, coalescing a burst into one write. Prepared messages are queued by reference.

Once a connection has a queue, its other data writes join the queue too: Write, WritePrepared, and fragmented sends enqueue their frames in submission order and return when those frames have been written, so message order and compressed-stream order are preserved and the two styles mix freely. Close joins it as well, so the close frame follows every message queued before it. Pings and pongs bypass the queue.

A Queue is safe for concurrent use.

Example
package main

import (
	"fmt"
	"net"

	"github.com/33TU/ews/codec"
	"github.com/33TU/ews/ws"
)

// examplePair connects a server and a client over an in-memory pipe. Real
// programs get the transport from ews.Upgrade, ews.Server or ews.Dial.
func examplePair() (server, client *ws.Conn) {
	sc, cc := net.Pipe()
	server, _ = ws.NewConn(sc, ws.Config{Role: ws.Server})
	client, _ = ws.NewConn(cc, ws.Config{Role: ws.Client})
	return server, client
}

func main() {
	server, client := examplePair()
	done := make(chan string)
	go func() {
		_, p, _ := client.ReadMessage()
		first := string(p)
		_, p, _ = client.ReadMessage()
		done <- first + " " + string(p)
	}()

	// Send returns once the message is queued; a goroutine writes it out.
	q := server.NewQueue(0)
	q.Send(codec.Text, []byte("queued"))
	// Synchronous writes join the queue in order.
	server.Write(codec.Text, []byte("ordered"))
	fmt.Println(<-done, q.Wait())
}
Output:
queued ordered <nil>

func (*Queue) Err

func (q *Queue) Err() error

Err returns the first write error, after which every Send fails with it.

func (*Queue) Pending

func (q *Queue) Pending() int

Pending returns the bytes queued but not yet handed to the transport.

func (*Queue) Send

func (q *Queue) Send(op codec.Opcode, payload []byte) error

Send encodes a text or binary message, compressing per the connection's settings, and queues it. payload is copied and may be reused at once.

func (*Queue) SendPrepared

func (q *Queue) SendPrepared(p *Prepared) error

SendPrepared queues a prepared message by reference, without copying, holding a reference to it until it has been written.

func (*Queue) Wait

func (q *Queue) Wait() error

Wait blocks until every queued frame has been written or the queue failed.

type Role

type Role uint8

Role identifies the local endpoint.

const (
	Server Role = iota
	Client
)

The two roles. A Server reads masked frames and writes unmasked ones; a Client does the reverse.

Jump to

Keyboard shortcuts

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