1
0
mirror of https://github.com/actix/actix-website synced 2025-02-02 12:19:04 +01:00

45 lines
1.2 KiB
Rust
Raw Normal View History

2019-06-17 18:07:57 -04:00
// <websockets>
2019-06-26 12:55:12 -04:00
use actix::{Actor, StreamHandler};
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
2019-06-17 18:07:57 -04:00
2020-09-12 16:21:54 +01:00
/// Define HTTP actor
2019-06-26 12:55:12 -04:00
struct MyWs;
2019-06-17 18:07:57 -04:00
2019-06-26 12:55:12 -04:00
impl Actor for MyWs {
type Context = ws::WebsocketContext<Self>;
}
2019-06-17 18:07:57 -04:00
2019-06-26 12:55:12 -04:00
/// Handler for ws::Message message
2019-12-29 04:16:54 +09:00
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
2022-02-26 03:56:24 +00:00
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
2019-06-26 12:55:12 -04:00
match msg {
2019-12-29 04:16:54 +09:00
Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
Ok(ws::Message::Text(text)) => ctx.text(text),
Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
2019-06-26 12:55:12 -04:00
_ => (),
}
}
}
2019-06-17 18:07:57 -04:00
2019-12-29 04:16:54 +09:00
async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
2019-06-26 12:55:12 -04:00
let resp = ws::start(MyWs {}, &req, stream);
println!("{:?}", resp);
resp
}
2020-09-12 16:21:54 +01:00
#[actix_web::main]
2019-12-29 04:16:54 +09:00
async fn main() -> std::io::Result<()> {
2019-06-26 12:55:12 -04:00
HttpServer::new(|| App::new().route("/ws/", web::get().to(index)))
2022-02-26 03:56:24 +00:00
.bind(("127.0.0.1", 8080))?
2019-06-26 12:55:12 -04:00
.run()
2019-12-29 04:16:54 +09:00
.await
2019-06-26 12:55:12 -04:00
}
2019-06-17 18:07:57 -04:00
// </websockets>
2019-06-26 12:55:12 -04:00
// testing requires specific headers:
// Upgrade: websocket
// Connection: Upgrade
// Sec-WebSocket-Key: SOME_KEY
// Sec-WebSocket-Version: 13