Expand description
Websocket integration.
§Examples
use actix::{Actor, StreamHandler};
use actix_web::{get, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
/// Define Websocket actor
struct MyWs;
impl Actor for MyWs {
type Context = ws::WebsocketContext<Self>;
}
/// Handler for ws::Message message
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
match msg {
Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
Ok(ws::Message::Text(text)) => ctx.text(text),
Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
_ => (),
}
}
}
#[get("/ws")]
async fn websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
ws::start(MyWs, &req, stream)
}
const MAX_FRAME_SIZE: usize = 16_384; // 16KiB
#[get("/custom-ws")]
async fn custom_websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
// Create a Websocket session with a specific max frame size, and protocols.
ws::WsResponseBuilder::new(MyWs, &req, stream)
.frame_size(MAX_FRAME_SIZE)
.protocols(&["A", "B"])
.start()
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(websocket)
.service(custom_websocket)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
Structs§
- Close
Reason - Reason for closing the connection
- Websocket
Context - Execution context for
WebSockets
actors - WsResponse
Builder - Builder for Websocket session response.
Enums§
- Close
Code - Status code used to indicate why an endpoint is closing the WebSocket connection.
- Frame
- A WebSocket frame.
- Handshake
Error - WebSocket handshake errors
- Message
- A WebSocket message.
- Protocol
Error - WebSocket protocol errors.
Functions§
- handshake
- Prepare WebSocket handshake response.
- handshake_
with_ protocols - Prepare WebSocket handshake response.
- start
- Perform WebSocket handshake and start actor.
- start_
with_ addr Deprecated - Perform WebSocket handshake and start actor.
- start_
with_ protocols Deprecated - Do WebSocket handshake and start ws actor.