ws

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

transport/ws

MQTT over WebSocket (ws://, wss://) for github.com/ashtonian/mqttv5, as a separate module so the core stays standard-library only.

import "github.com/ashtonian/mqttv5/transport/ws"

cli, err := mqttv5.New(
    mqttv5.WithBroker("wss://broker.example.com/mqtt"),
    mqttv5.WithDialFunc(ws.DialFunc(ws.DialOpts{})),
)
Module github.com/ashtonian/mqttv5/transport/ws
Depends on github.com/ashtonian/mqttv5, github.com/gobwas/ws v1.4.0
Spec MQTT v5.0 §6 (WebSocket transport), RFC 6455

Overview

DialFunc returns a function for mqttv5.WithDialFunc. Each connection attempt performs the HTTP upgrade with subprotocol mqtt, then carries the MQTT byte stream in WebSocket binary frames:

  • Writes. Every MQTT packet the client writes goes out as one masked binary frame, in a single write to the socket.
  • Reads. Frames are reassembled into the byte stream the MQTT decoder reads, however the broker fragments them. Frames the broker sends right behind its handshake response are not lost.
  • Control frames. A Ping is answered with a Pong carrying its payload; a Close is answered with a Close and ends the connection (the client's supervisor then reconnects). Pongs and close replies are written under the same lock as data frames, so they never split one.
  • Text frames from the broker close the connection with ErrTextFrame: MQTT travels only in binary frames MQTT-6.0.0-1.
  • TLS. wss:// verifies the broker against the system roots unless DialOpts.TLSConfig says otherwise, like mqtts://; the URL's host is the server name when TLSConfig.ServerName is empty.

mqttv5.New rejects ws:// and wss:// broker URLs unless WithDialFunc is set.

Configuration

DialOpts; the zero value is valid.

Field Type Default Description
TLSConfig *tls.Config system roots, server name from the URL TLS for wss://; ignored for ws://.
HTTPHeaders http.Header none Added to the upgrade request: auth tokens, routing headers.
Subprotocols []string ["mqtt"] Sec-WebSocket-Protocol values offered.
HandshakeTimeout time.Duration DefaultHandshakeTimeout (10 s) Bound on the upgrade handshake. The client's connect timeout (mqttv5.WithConnectTimeout) bounds the whole attempt as well.
CloseFrameTimeout time.Duration DefaultCloseFrameTimeout (1 s) Bound on the Close frame sent when the connection closes. Close skips the frame when a write is in progress, which may be stalled behind a broker that stopped reading, and closes the socket at once.
NetDial func(ctx, network, addr string) (net.Conn, error) net.Dialer Replaces the TCP dial, e.g. for a proxy.

The URL's path and query go into the upgrade request (wss://host/mqtt); a missing port means 80 for ws:// and 443 for wss://.

External dependencies

Module Version Used for
github.com/gobwas/ws v1.4.0 upgrade handshake, frame headers, control-frame replies

API

Symbol Description
DialFunc(DialOpts) transport.DialFunc For mqttv5.WithDialFunc.
Dial(ctx, *url.URL, DialOpts) (transport.Conn, error) One upgrade, outside the client.
DialOpts See Configuration.
DefaultHandshakeTimeout 10 s.
DefaultCloseFrameTimeout 1 s.
ErrTextFrame The broker sent a text frame.
Conn The transport.Conn that Dial returns; treat it as opaque.

Build, run, test

go -C transport/ws test -race ./...

The tests run against an in-process WebSocket server: round trips, byte-at-a-time reads, ping/pong under concurrent writes, broker Close, text frames, closing during a stalled write, and TLS verification. examples/ws connects to a real broker.

Operations

Symptom Check Then
dial … : unexpected HTTP response status the URL path and the broker's WebSocket listener Most brokers serve MQTT on a path such as /mqtt.
x509: certificate signed by unknown authority the broker's certificate chain Add its CA to DialOpts.TLSConfig.RootCAs.
Connections drop every few minutes behind a proxy the proxy's idle timeout and whether it pings Pings are answered; lower mqttv5.WithKeepAlive below the proxy's idle timeout.
The broker logs connections ending without a Close frame whether the client was writing when it closed Expected when a write was in progress or the broker stopped reading: Close does not wait for a write, and sends the Close frame for at most CloseFrameTimeout.
ErrTextFrame the broker or a proxy injecting text frames MQTT over WebSocket allows binary frames only; fix the peer.

Connection-level health and counters come from the client (Client.Stats(), the lifecycle callbacks); this package logs nothing.

Security

  • wss:// verifies the broker's certificate by default. Do not set InsecureSkipVerify outside tests.
  • HTTPHeaders may carry credentials; they are sent on every connection attempt and never logged.
  • Client frames are masked as RFC 6455 requires, with a fresh mask per frame.

Code map

File What
ws.go DialFunc, Dial, Conn (framing, control frames)
ws_test.go dialing, round trips, TLS
control_test.go ping/pong, close, text frames, concurrent writes

Documentation

Overview

Package ws is the WebSocket transport for mqttv5. It is a sibling submodule with its own go.mod so the core mqttv5 module stays stdlib-only. Wire it up via DialFunc:

cli, _ := mqttv5.New(
    mqttv5.WithBroker("wss://broker.example/mqtt"),
    mqttv5.WithDialFunc(ws.DialFunc(ws.DialOpts{
        TLSConfig: tlsCfg,
    })),
)

Both ws:// and wss:// are first-class. Like mqtts://, wss:// without a DialOpts.TLSConfig verifies the broker against the system roots with the URL's host as the server name.

External dependency: github.com/gobwas/ws — chosen for its low per-frame allocation profile, in line with mqttv5's allocation-free decoder.

Index

Constants

View Source
const DefaultCloseFrameTimeout = time.Second

DefaultCloseFrameTimeout bounds the Close frame Conn.Close sends, when DialOpts.CloseFrameTimeout is zero.

View Source
const DefaultHandshakeTimeout = 10 * time.Second

DefaultHandshakeTimeout is the WebSocket upgrade-handshake budget used when DialOpts.HandshakeTimeout is zero.

Variables

View Source
var ErrTextFrame = errors.New("mqttv5/transport/ws: text frame from the broker")

ErrTextFrame reports a WebSocket text frame from the broker. MQTT travels only in binary frames; any other data frame must close the connection [MQTT-6.0.0-1].

Functions

func Dial

func Dial(ctx context.Context, brokerURL *url.URL, opts DialOpts) (transport.Conn, error)

Dial performs the WebSocket upgrade against brokerURL and returns a transport.Conn that frames every Read/Write as a single MQTT control packet (per MQTT-over-WS §6 — "single WebSocket data frame"). Prefer DialFunc when wiring into mqttv5.WithDialFunc; call Dial directly when you need a one-shot upgrade outside the client.

func DialFunc

func DialFunc(opts DialOpts) transport.DialFunc

DialFunc binds opts and returns a transport.DialFunc that's directly compatible with mqttv5.WithDialFunc — typical usage:

mqttv5.WithDialFunc(ws.DialFunc(ws.DialOpts{TLSConfig: tlsCfg}))

Equivalent to writing the closure by hand around Dial; provided because the closure form reads poorly when several broker options are stacked together.

Types

type Conn

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

Conn wraps a websocket connection so every Write is one WebSocket frame holding one MQTT control packet. It is created by Dial; callers should treat the returned transport.Conn as opaque.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the underlying connection, first sending a Close frame when no write is in progress, within DialOpts.CloseFrameTimeout. A write in progress is not waited for: it may be stalled behind a peer that stopped reading, and closing the connection is what ends it.

func (*Conn) LocalAddr

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

LocalAddr forwards to the underlying connection.

func (*Conn) Read

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

Read returns the next available bytes from the MQTT byte stream. Each underlying WebSocket binary frame is one MQTT control packet, but the MQTT decoder reads field-at-a-time — so Read may be called many times per frame. Between frames it answers Ping with Pong and Close with Close (then reports io.EOF); a text frame is an error.

func (*Conn) RemoteAddr

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

RemoteAddr forwards to the underlying connection.

func (*Conn) SetDeadline

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

SetDeadline forwards to the underlying connection.

func (*Conn) SetReadDeadline

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

SetReadDeadline forwards to the underlying connection.

func (*Conn) SetWriteDeadline

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

SetWriteDeadline forwards to the underlying connection.

func (*Conn) Write

func (c *Conn) Write(p []byte) (int, error)

Write emits p as one masked WebSocket binary frame in a single write to the connection. p is not modified.

type DialOpts

type DialOpts struct {
	// TLSConfig configures TLS for wss:// URLs and is ignored for
	// ws://. Nil verifies against the system roots; an empty ServerName
	// is filled in from the URL's host.
	TLSConfig *tls.Config

	// HTTPHeaders are added to the HTTP upgrade request — useful for
	// auth tokens, custom routing headers, etc.
	HTTPHeaders http.Header

	// Subprotocols sent in Sec-WebSocket-Protocol. Defaults to
	// []string{"mqtt"} per MQTT v5 §6.
	Subprotocols []string

	// HandshakeTimeout bounds the upgrade handshake. Defaults to
	// DefaultHandshakeTimeout.
	HandshakeTimeout time.Duration

	// CloseFrameTimeout bounds the Close frame sent when the connection
	// is closed. Defaults to DefaultCloseFrameTimeout.
	CloseFrameTimeout time.Duration

	// NetDial overrides the underlying TCP dial. Use this to inject a
	// SOCKS / HTTP CONNECT proxy or a custom net.Dialer.
	NetDial func(ctx context.Context, network, addr string) (net.Conn, error)
}

DialOpts customises a Dial call. Zero value is valid.

Jump to

Keyboard shortcuts

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