Skip to content
CryoCryo home
Stdlibnet::ws

connection

import std::net::ws::connection; · source

Types

WebSocket<S>

type struct WebSocket<S> {
    private conn:              BufferedStream<S>;
    private is_client:         boolean;
    private closed:            boolean;
    private peer_close_code:   u16;
    private peer_close_reason: String;
}

A WebSocket<S> owns a BufferedStream<S> over any AsyncTransport. connect(socket, host, path) and accept(socket) wrap a plain TcpStream and run the handshake in one step. For a TLS transport, or to control the buffering, build with of(connection, is_client) and call client_handshake(host, path) or server_handshake() yourself. The handshake is an HTTP/1.1 Upgrade; bytes that arrive after its blank line stay buffered for the first receive.

import std::io::buffered::{ BufferedStream };
import std::io::error::{ IoError };
import std::net::tls::stream::{ TlsStream };
import std::net::ws::connection::{ WebSocket };

async function open_secure(tls: TlsStream, host: Str, path: Str) -> Result<WebSocket<TlsStream>, IoError> {
    mut ws: WebSocket<TlsStream> = WebSocket::<TlsStream>::of(BufferedStream::<TlsStream>::of(tls), true);
    (await ws.client_handshake(host, path))?;
    return Result::Ok(ws);
}

The message surface is send_text, send_binary, ping, close(code, reason), and receive — all async. Framing covers text and binary messages, fragmentation reassembly, and the Ping/Pong/Close control frames. receive yields application messages only: it answers a Ping with a Pong itself, skips incoming Pongs, and surfaces a Close frame as Message::Close, after answering it with a Close echoing its status code unless this side already sent one. close_status() then reports the peer's code and reason. A bounded number of control frames is serviced per receive, so a peer flooding pings cannot keep the call from ever returning. is_closed() reports whether a close has been sent or received; connection() surfaces the transport for socket options, not for I/O.

A protocol violation by the peer is InvalidData, and receive answers it before reporting it: a Close whose status code or reason breaks the protocol, or a frame masked the wrong way, with CLOSE_PROTOCOL_ERROR or CLOSE_INVALID_PAYLOAD; a text message that is not UTF-8 with CLOSE_INVALID_PAYLOAD.

Clients mask every frame they send and servers must not, as the RFC requires; is_client is what decides, and a frame arriving with the wrong masking is a protocol error.

Constructors

static of(conn: BufferedStream<S>, is_client: boolean) -> WebSocket<S>;

Take ownership of an already-upgraded connection. is_client selects masked (client) vs unmasked (server) framing per RFC 6455. Use client_handshake / server_handshake to run the upgrade first.

Methods

connection(mut &this) -> mut BufferedStream<S>*;

The buffered connection, for callers that need the transport itself (socket options, the negotiated ALPN protocol). Not for reading or writing — that would desynchronize the framing.

is_closed(&this) -> boolean;

Has a Close frame been sent or received on this connection?

close_status(&this) -> Option<CloseStatus>;

The status code and reason of the Close frame the peer sent, once receive has returned Message::Close for it; None before that, and for a Close that broke the protocol, which receive reports as an error.

async client_handshake(mut &this, host: Str, path: Str) -> Result<(), IoError> where S: AsyncTransport;

Client handshake: send the GET upgrade, then verify the 101 and the Sec-WebSocket-Accept echo. Bytes that arrived after the blank line stay buffered for receive.

async server_handshake(mut &this) -> Result<(), IoError> where S: AsyncTransport;

Server handshake: read the client GET, reply 101 with the computed accept value. Bytes that arrived after the blank line — a client that pipelined its first frame into the same write — stay buffered.

async send_text(mut &this, text: Str) -> Result<(), IoError> where S: AsyncTransport;

Send a text message in a single frame.

async send_binary(mut &this, data: &Slice<u8>) -> Result<(), IoError> where S: AsyncTransport;

Send a binary message in a single frame.

async ping(mut &this, data: &Slice<u8>) -> Result<(), IoError> where S: AsyncTransport;

Send a Ping with optional application data.

async close(mut &this, code: u16, reason: Str) -> Result<(), IoError> where S: AsyncTransport;

Send a Close frame with a status code and reason. The transport itself is closed when the WebSocket is dropped.

async receive(mut &this) -> Result<Message, IoError> where S: AsyncTransport;

Receive the next application message, reassembling fragments and transparently answering Pings with Pongs and skipping Pongs. A Close frame surfaces as Message::Close, after being answered with a Close echoing its status code unless this side already sent one; its code and reason are then close_status. A Close whose status code or reason breaks the protocol is answered with CLOSE_PROTOCOL_ERROR or CLOSE_INVALID_PAYLOAD instead and reported as InvalidData, as is a text message that is not UTF-8, which is answered with CLOSE_INVALID_PAYLOAD, and a frame masked the wrong way for this

Message

type enum Message {
    Text(String);
    Binary(Array<u8>);
    Close;
}

What receive yields: a reassembled text or binary message, owning its payload, or the peer's close.

Variants
Variant
Text(String)
Binary(Array<u8>)
Close

CloseStatus

type struct CloseStatus {
    code:   u16;
    reason: Str;
}

The status code and reason of the Close frame the peer sent, as close_status() reports them. The code is CLOSE_NO_STATUS_RECEIVED when the peer's Close carried none; the reason is a view of the connection's copy, valid while the WebSocket is.

Properties
PropertyTypeNotes
codeu16The peer's status code; CLOSE_NO_STATUS_RECEIVED when its Close carried none.
reasonStrThe peer's reason, UTF-8 and possibly empty. A view of the connection's copy, valid while the WebSocket is.

Trait implementations

implement<S> trait Drop for struct WebSocket<S>

Dropping the socket drops the connection. Send close first if you want the peer to see a clean shutdown rather than a reset.

Free Functions

async function connect(sock: TcpStream, host: Str, path: Str) -> Result<WebSocket<TcpStream>, IoError>;

Connect a WebSocket over an already-connected TCP socket: wrap it, run the client handshake, and hand back the upgraded connection. The socket is consumed — the WebSocket owns it from here.

The one-step client constructor over a plain TcpStream: runs the opening handshake against host and path and returns a ready WebSocket<TcpStream>.

async function accept(sock: TcpStream) -> Result<WebSocket<TcpStream>, IoError>;

Accept a WebSocket over an accepted TCP socket: wrap it, run the server handshake, and hand back the upgraded connection.

The server-side counterpart: answers a client's upgrade request on an accepted TcpStream and returns the ready WebSocket<TcpStream>.

Constants

The status codes a Close frame carries.

const CLOSE_NORMAL:              u16 = 1000;
const CLOSE_GOING_AWAY:          u16 = 1001;
const CLOSE_PROTOCOL_ERROR:      u16 = 1002;
const CLOSE_UNSUPPORTED_DATA:    u16 = 1003;
const CLOSE_INVALID_PAYLOAD:     u16 = 1007;
const CLOSE_POLICY_VIOLATION:    u16 = 1008;
const CLOSE_MESSAGE_TOO_BIG:     u16 = 1009;
const CLOSE_MANDATORY_EXTENSION: u16 = 1010;
const CLOSE_INTERNAL_ERROR:      u16 = 1011;
const CLOSE_NO_STATUS_RECEIVED:  u16 = 1005;