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>;
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>*;
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;
is_closed(&this) -> boolean;Has a Close frame been sent or received on this connection?
close_status(&this) -> Option<CloseStatus>;
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;
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;
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;
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;
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;
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;
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;
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
| Property | Type | Notes |
|---|---|---|
code | u16 | The peer's status code; CLOSE_NO_STATUS_RECEIVED when its Close carried none. |
reason | Str | The 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>;
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>;
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;type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct WebSocket<S> {}A WebSocket connection over the buffered async transport S - TcpStream for ws://, TlsStream for wss://. Owns the connection and records which side it is, which decides the frame masking: a client masks what it sends and refuses masked frames, a server the reverse.
type parameter Sprivate type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
WebSocket.conn: BufferedStream<S>type struct BufferedStream<S> {}A buffered connection for asynchronous code: it owns its transport S (a socket or a TLS session) and buffers both directions, so many small reads and writes become few large ones. It implements AsyncRead and AsyncWrite; make one with of.
type parameter SWebSocket.is_client: booleanWebSocket.closed: booleanWebSocket.peer_close_code: u16WebSocket.peer_close_reason: Stringtype struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
type struct IoError {
kind: IoErrorKind;
os_code: i32;
}The error of a failed I/O operation: its kind, the operating system's own code, and, when the operation named one, what it was doing and the path. It prints as could not open config.toml: not found.
type struct TlsStream {}An encrypted connection: an OpenSSL session over a TcpStream, made by TlsConnector::connect or TlsAcceptor::accept. Bytes move through its AsyncTransport implementation, directly or buffered as BufferedStream<TlsStream>, exactly as over a plain TcpStream.
namespace std::net::ws::connection;WebSocket connection: handshake + message send/receive over a buffered async connection.
module pagetype struct WebSocket<S> {}A WebSocket connection over the buffered async transport S - TcpStream for ws://, TlsStream for wss://. Owns the connection and records which side it is, which decides the frame masking: a client masks what it sends and refuses masked frames, a server the reverse.
async function name(param: Type) -> T { ... }Compiles the function into a stackless state machine. Calling it builds a future whose output is the declared return type; nothing runs until that future is polled. Allowed on free functions, methods, and trait methods.
language referencefunction name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
async function open_secure(tls: TlsStream, host: Str, path: Str) -> Result<WebSocket<TlsStream>, IoError>(parameter) tls: TlsStream(parameter) host: Strtype struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
(parameter) path: Strtype enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut ws: WebSocket<TlsStream>static WebSocket::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.
static BufferedStream::of(inner: S) -> BufferedStream<S>Wrap an already-connected transport.
std::io::buffered(parameter) tls: TlsStreamtrueThe boolean literal. Booleans are a distinct 1-byte type, not interchangeable with integers; if and while conditions must be boolean.
await futureSuspends the enclosing async body until the operand - which must implement Future - completes, and evaluates to its output. A prefix operator allowed anywhere an expression is (conditions, arms, guards), but only inside async code.
mut ws: WebSocket<TlsStream>async WebSocket::client_handshake(mut &this, host: Str, path: Str) -> Result<(), IoError>
where S: AsyncTransportClient 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.
(parameter) host: Str(parameter) path: Strvalue?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. It works on any type implementing Try, in a function whose return type implements FromResidual of it; an error of another type converts through From.
return value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
Result::Ok(T)type enum Name {
Unit,
Payload(T),
Named { x: i32 },
}An algebraic data type. Variants may be bare or carry a tuple or struct payload, and a match on an enum must cover every variant. Name::Variant names a variant; methods are added with implement enum Name { ... }.
type enum Message {
Text(String);
Binary(Array<u8>);
Close;
}A complete application message. Owns its payload.
Message::Text(String)Message::Binary(Array<u8>)type struct Array<T, A = GlobalAllocator> where A: Allocator {}A growable sequence of Ts stored contiguously, owning its elements; A is the allocator its storage comes from. Indexing out of range panics; get answers None instead.
Message::Closetype struct CloseStatus {
code: u16;
reason: Str;
}The status code and reason of the Close frame a peer sent, as WebSocket.close_status reports them.
CloseStatus.code: u16The peer's status code; CLOSE_NO_STATUS_RECEIVED when its Close carried none.
CloseStatus.reason: StrThe peer's reason, UTF-8 and possibly empty. A view of the connection's copy, valid while the WebSocket is.
const NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
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;type trait AsyncTransport {
async read_into(mut &this, buf: Array<u8>) -> Transfer;
async write_from(mut &this, buf: Array<u8>) -> Transfer;
}One raw, unbuffered async byte channel: what BufferedStream<S> needs of a transport, and nothing more.
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.
extern "C" function socket(domain: AddressFamily, sock_type: i32, protocol: Protocol) -> i32socket is also declared in std::sys::syscall
std::ffi::libcasync 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.
std::net::ws::connectiontype struct TcpStream {}A connected TCP socket. Comes from TcpStream::connect (client) or listener.accept() (server), both of which leave it in non-blocking mode; bytes move through read_some and write_all, or through BufferedStream<TcpStream> via its AsyncTransport implementation. Owns its socket and closes it on drop.
WebSocket::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.
std::net::ws::connectionasync WebSocket::server_handshake(mut &this) -> Result<(), IoError>
where S: AsyncTransportServer 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 WebSocket::receive(mut &this) -> Result<Message, IoError>
where S: AsyncTransportReceive 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.
async WebSocket::send_text(mut &this, text: Str) -> Result<(), IoError>
where S: AsyncTransportSend a text message in a single frame.
std::net::ws::connectionasync WebSocket::send_binary(mut &this, data: &Slice<u8>) -> Result<(), IoError>
where S: AsyncTransportSend a binary message in a single frame.
std::net::ws::connectionasync WebSocket::ping(mut &this, data: &Slice<u8>) -> Result<(), IoError>
where S: AsyncTransportSend a Ping with optional application data.
std::net::ws::connectionasync WebSocket::close(mut &this, code: u16, reason: Str) -> Result<(), IoError>
where S: AsyncTransportSend a Close frame with a status code and reason. The transport itself is closed when the WebSocket is dropped.
CloseStatus.code: u16The peer's status code; CLOSE_NO_STATUS_RECEIVED when its Close carried none.
CloseStatus.reason: StrThe peer's reason, UTF-8 and possibly empty. A view of the connection's copy, valid while the WebSocket is.
Message::Closetype enum Message {
Text(String);
Binary(Array<u8>);
Close;
}A complete application message. Owns its payload.
std::net::ws::connectionWebSocket::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.
WebSocket::is_closed(&this) -> booleanHas a Close frame been sent or received on this connection?
std::net::ws::connectionIoErrorKind::InvalidDataThe bytes do not have the form the operation needs, such as text that is not UTF-8.
std::io::errorconst CLOSE_PROTOCOL_ERROR: u16 = 1002;const CLOSE_INVALID_PAYLOAD: u16 = 1007;static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
(parameter) conn: BufferedStream<S>(parameter) is_client: booleanmut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
type struct CloseStatus {
code: u16;
reason: Str;
}The status code and reason of the Close frame a peer sent, as WebSocket.close_status reports them.
Option::Noneprimitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
where T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
(parameter) text: Str(parameter) data: &Slice<u8>type struct Slice<T> {}The elements are reached through ptr, declared read-only: through a mut &Slice<T> it reads as a writable pointer, through a &Slice<T> as the read-only one it is.
(parameter) code: u16(parameter) reason: StrMessage::Text(String)Message::Binary(Array<u8>)const CLOSE_NO_STATUS_RECEIVED: u16 = 1005;implement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
type trait Drop {
drop(mut &this) -> void;
}A type that releases something when a value of it ends: memory, a file handle, a lock. The compiler calls drop once when an owned value goes out of scope; release a value early with mem::drop(value).
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referenceasync 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.
(parameter) sock: TcpStreamasync 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.