Expand description
A websocket service for actix-web framework.
§Example:
use actix_web::{get, App, Error, HttpRequest, HttpServer, Responder};
use actix_send_websocket::{Message, WebSocket};
#[get("/")]
async fn ws(ws: WebSocket) -> impl Responder {
// stream is the async iterator of incoming client websocket messages.
// res is the response we return to client.
// tx is a sender to push new websocket message to client response.
let (mut stream, res, mut tx) = ws.into_parts();
// spawn the stream handling so we don't block the response to client.
actix_web::rt::spawn(async move {
while let Some(Ok(msg)) = stream.next().await {
let result = match msg {
// we echo text message and ping message to client.
Message::Text(string) => tx.text(string),
Message::Ping(bytes) => tx.pong(&bytes),
Message::Close(reason) => {
let _ = tx.close(reason);
// force end the stream when we have a close message.
break;
}
// other types of message would be ignored
_ => Ok(()),
};
if result.is_err() {
// end the stream when the response is gone.
break;
}
}
});
res
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(ws))
.bind("127.0.0.1:8080")?
.run()
.await
}
§Features
Structs§
- Reason for closing the connection
- WebSockets protocol codec
- extractor type for websocket.
- config for WebSockets.
Enums§
- Status code used to indicate why an endpoint is closing the
WebSocket
connection. WebSocket
frame- Websocket handshake errors
WebSocket
Message- Websocket protocol errors
Functions§
- Prepare
WebSocket
handshake response. - Prepare
WebSocket
handshake response. - split stream into decode/encode streams and a sender that can send item to encode stream.