Documentation
¶
Overview ¶
Package ws provides message I/O over already-upgraded WebSocket connections.
A Conn wraps any io.ReadWriter; the caller keeps the net.Conn for deadlines, TLS and closing, and NetConn hands it 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; 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. 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. Outgoing text is never validated: the sender knows its data.
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 ¶
- Constants
- Variables
- func NetConn(c *Conn, op codec.Opcode) net.Conn
- func Serve(c *Conn, h MessageHandler) error
- type CloseError
- type Config
- type Conn
- func (c *Conn) BeginMessage(op codec.Opcode) error
- func (c *Conn) Close(code uint16, reason string) error
- func (c *Conn) CloseSent() bool
- func (c *Conn) EndMessage() error
- func (c *Conn) NewQueue(limit int) *Queue
- func (c *Conn) NextMessage() (codec.Opcode, error)
- func (c *Conn) Ping(payload []byte) error
- func (c *Conn) Pong(payload []byte) error
- func (c *Conn) Read(b []byte) (int, error)
- func (c *Conn) ReadMessage() (codec.Opcode, []byte, error)
- func (c *Conn) Write(op codec.Opcode, payload []byte) error
- func (c *Conn) WriteChunk(payload []byte) error
- func (c *Conn) WriteFrom(op codec.Opcode, r io.Reader) (int64, error)
- func (c *Conn) WritePrepared(p *Prepared) error
- func (c *Conn) WriteTo(w io.Writer) (int64, error)
- type ControlHandler
- type DefaultControlHandler
- type Error
- type MessageFunc
- type MessageHandler
- type Prepared
- type Queue
- type Role
Examples ¶
Constants ¶
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 )
const NoStatus = 1005
NoStatus is the close code reported when the peer sent none.
Variables ¶
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") )
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 ¶
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 when it is a net.Conn, 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. Other transports report errors.ErrUnsupported for deadlines and a placeholder address. 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 ¶
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
// compressed write instead of keeping one attached to the connection.
// 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. Without send
// context takeover compressors are always shared.
CompressionShared bool
// ControlHandler replaces the defaults. Nil uses DefaultControlHandler.
ControlHandler ControlHandler
}
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(rw io.ReadWriter, cfg Config) (*Conn, error)
NewConn wraps an upgraded transport.
func (*Conn) BeginMessage ¶
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 ¶
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.
func (*Conn) EndMessage ¶
EndMessage sends the final, empty fragment of the open message.
func (*Conn) NewQueue ¶
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 ¶
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) Pong ¶
Pong sends a pong with at most 125 payload bytes. Pongs are allowed after Close.
func (*Conn) Read ¶
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 ¶
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) Write ¶
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 ¶
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 ¶
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 ¶
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 ¶
WriteTo writes the rest of the current message to w, so io.Copy(w, c) moves a message without a buffer of its own. 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. 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.
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. Shared handlers must support concurrent calls from different connections. Payloads are borrowed for the duration of each call. Handlers replace defaults: OnPing must send a Pong, and OnClose a close response if needed. They may write but must not read from c. 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.
type 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.
type MessageFunc ¶ added in v0.2.0
MessageFunc adapts a function to MessageHandler.
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 ¶
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.
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. Control frames 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) Send ¶
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 ¶
SendPrepared queues a prepared message by reference, without copying, holding a reference to it until it has been written.