2020-06-19 21:38:11 +02:00
|
|
|
use actix::prelude::*;
|
|
|
|
use actix_web::{middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer};
|
|
|
|
use actix_web_actors::ws;
|
|
|
|
|
|
|
|
async fn ws_index(r: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
|
2023-07-08 19:51:57 +02:00
|
|
|
ws::start(AutobahnWebSocket, &r, stream)
|
2020-06-19 21:38:11 +02:00
|
|
|
}
|
|
|
|
|
2022-02-18 02:44:53 +01:00
|
|
|
#[derive(Debug, Clone, Default)]
|
|
|
|
struct AutobahnWebSocket;
|
2020-06-19 21:38:11 +02:00
|
|
|
|
2022-02-18 02:44:53 +01:00
|
|
|
impl Actor for AutobahnWebSocket {
|
2020-06-19 21:38:11 +02:00
|
|
|
type Context = ws::WebsocketContext<Self>;
|
|
|
|
}
|
|
|
|
|
2022-02-18 02:44:53 +01:00
|
|
|
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for AutobahnWebSocket {
|
2022-02-18 03:44:02 +01:00
|
|
|
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
|
2020-06-19 21:38:11 +02:00
|
|
|
if let Ok(msg) = msg {
|
|
|
|
match msg {
|
|
|
|
ws::Message::Text(text) => ctx.text(text),
|
|
|
|
ws::Message::Binary(bin) => ctx.binary(bin),
|
|
|
|
ws::Message::Ping(bytes) => ctx.pong(&bytes),
|
2020-06-25 06:20:27 +02:00
|
|
|
ws::Message::Close(reason) => {
|
|
|
|
ctx.close(reason);
|
|
|
|
ctx.stop();
|
|
|
|
}
|
2020-06-19 21:38:11 +02:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
ctx.stop();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-12 17:49:45 +02:00
|
|
|
#[actix_web::main]
|
2020-06-19 21:38:11 +02:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2022-02-18 02:44:53 +01:00
|
|
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
|
|
|
|
|
|
|
log::info!("starting HTTP server at http://localhost:9001");
|
2020-06-19 21:38:11 +02:00
|
|
|
|
|
|
|
HttpServer::new(|| {
|
|
|
|
App::new()
|
|
|
|
.wrap(middleware::Logger::default())
|
|
|
|
.service(web::resource("/").route(web::get().to(ws_index)))
|
|
|
|
})
|
2022-02-18 02:44:53 +01:00
|
|
|
.workers(2)
|
|
|
|
.bind(("127.0.0.1", 9001))?
|
2020-06-19 21:38:11 +02:00
|
|
|
.run()
|
|
|
|
.await
|
|
|
|
}
|