fastwebsockets-stream
fastwebsockets-stream provides alightweight adapter that exposes a fastwebsockets::WebSocket<S>
as a tokio-compatible byte stream by implementing AsyncRead and AsyncWrite.
It makes it easy to layer existing codecs (for example tokio_util::codec::Framed) or to
reuse I/O-based logic over WebSocket application payloads without reimplementing
WebSocket framing.
Features
- Converts a
fastwebsockets::WebSocketinto a byte stream. - Supports
BinaryandTextpayloads viaPayloadType. - Implements both
AsyncReadandAsyncWritetraits. - Handles control frames (Ping/Pong/Close) automatically through the
underlying
fastwebsocketssettings. - Integrates seamlessly with the [
fastwebsockets] crate andtokioecosystem.
Example: Server
use ;
use ;
use ;
use ;
use http1;
use service_fn;
use TokioIo;
use Empty;
use ;
use Ipv4Addr;
async
async
Example: Client
use ;
use ;
use Empty;
use ;
use Bytes;
use TcpStream;
async
API overview
WebSocketStream<S>
An adapter type that implements tokio::io::AsyncRead and
tokio::io::AsyncWrite for a wrapped fastwebsockets::WebSocket<S>.
Important behaviors:
- Reads present application data frames (Text/Binary) as a continuous byte stream. If a single websocket frame's payload is larger than the caller's read buffer, the remainder is buffered internally and delivered by subsequent reads.
- A
Closeframe is mapped to EOF; subsequent reads returnOk(())with zero bytes. - Writes produce exactly one WebSocket data frame per call to
write. - The adapter temporarily takes ownership of the inner
WebSocketwhile an asynchronous read or write operation is in flight.into_inner()will return the innerWebSocketonly if it is not currently owned by an outstanding future.
Key methods:
WebSocketStream::new(websocket, payload_type)— create a new adapter.into_inner(self) -> Option<WebSocket<S>>— attempt to recover the inner websocket if no operation is in-progress.is_closed(&self) -> bool— returnstrueif a Close frame was observed.
PayloadType
Enum with variants Binary and Text specifying which opcode the stream
expects and will emit.
Usage tips
-
If you want to use a codec that frames logical application-level messages (for example
LinesCodec, length-delimited frames, or protobuf), combineWebSocketStreamwithtokio_util::codec::Framed. -
Remember that each call to
writebecomes a single websocket frame. If your application expects to stream a single large logical message in several frames, implement that message-level framing in your codec.
License
Licensed under the MIT License. See LICENSE for details.