Crate fastwebsockets
source ·Expand description
fastwebsockets is a minimal, fast WebSocket server implementation.
https://github.com/littledivy/fastwebsockets
Passes the Autobahn|TestSuite and fuzzed with LLVM’s libfuzzer.
You can use it as a raw websocket frame parser and deal with spec compliance yourself, or you can use it as a full-fledged websocket server.
Example
ⓘ
use tokio::net::TcpStream;
use fastwebsockets::{WebSocket, OpCode};
async fn handle_client(
socket: TcpStream,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Perform the WebSocket handshake
let socket = handshake(socket).await?;
let mut ws = WebSocket::after_handshake(socket);
ws.set_writev(false);
ws.set_auto_close(true);
ws.set_auto_pong(true);
loop {
let frame = ws.read_frame().await?;
match frame.opcode {
OpCode::Close => break,
OpCode::Text | OpCode::Binary => {
ws.write_frame(frame).await?;
}
_ => {}
}
}
Ok(())
}
Fragmentation
By default, fastwebsockets will give the application raw frames with FIN set. Other crates like tungstenite which will give you a single message with all the frames concatenated.
For concanated frames, use FragmentCollector
:
ⓘ
use fastwebsockets::{FragmentCollector, WebSocket};
let mut ws = WebSocket::after_handshake(socket);
let mut ws = FragmentCollector::new(ws);
let incoming = ws.read_frame().await?;
// Always returns full messages
assert!(incoming.fin);
permessage-deflate is not supported yet.
Structs
- Collects fragmented messages over a WebSocket connection and returns the completed message once all fragments have been received.
- Represents a WebSocket frame.
- WebSocket protocol implementation over an async stream.
Enums
- Status code used to indicate why an endpoint is closing the WebSocket connection.
Functions
- Unmask a payload using the given 4-byte mask.