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

45 lines
1.1 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
2019-06-26 12:55:12 -04:00
/// Define http actor
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
impl StreamHandler<ws::Message, ws::ProtocolError> for MyWs {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
match msg {
ws::Message::Ping(msg) => ctx.pong(&msg),
ws::Message::Text(text) => ctx.text(text),
ws::Message::Binary(bin) => ctx.binary(bin),
_ => (),
}
}
}
2019-06-17 18:07:57 -04:00
2019-06-26 12:55:12 -04:00
fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
let resp = ws::start(MyWs {}, &req, stream);
println!("{:?}", resp);
resp
}
fn main() {
HttpServer::new(|| App::new().route("/ws/", web::get().to(index)))
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}
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