2019-03-18 06:02:03 +01:00
|
|
|
use actix::prelude::*;
|
2019-12-15 17:45:38 +01:00
|
|
|
use actix_web::{test, web, App, HttpRequest};
|
2019-03-18 06:02:03 +01:00
|
|
|
use actix_web_actors::*;
|
2019-12-15 17:45:38 +01:00
|
|
|
use bytes::Bytes;
|
|
|
|
use futures::{SinkExt, StreamExt};
|
2019-03-18 06:02:03 +01:00
|
|
|
|
|
|
|
struct Ws;
|
|
|
|
|
|
|
|
impl Actor for Ws {
|
2019-03-18 06:11:50 +01:00
|
|
|
type Context = ws::WebsocketContext<Self>;
|
2019-03-18 06:02:03 +01:00
|
|
|
}
|
|
|
|
|
2019-12-15 17:45:38 +01:00
|
|
|
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Ws {
|
|
|
|
fn handle(
|
|
|
|
&mut self,
|
|
|
|
msg: Result<ws::Message, ws::ProtocolError>,
|
|
|
|
ctx: &mut Self::Context,
|
|
|
|
) {
|
|
|
|
match msg.unwrap() {
|
2019-03-18 06:31:10 +01:00
|
|
|
ws::Message::Ping(msg) => ctx.pong(&msg),
|
|
|
|
ws::Message::Text(text) => ctx.text(text),
|
|
|
|
ws::Message::Binary(bin) => ctx.binary(bin),
|
|
|
|
ws::Message::Close(reason) => ctx.close(reason),
|
2019-03-18 06:02:03 +01:00
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-15 17:45:38 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_simple() {
|
|
|
|
let mut srv = test::start(|| {
|
|
|
|
App::new().service(web::resource("/").to(
|
|
|
|
|req: HttpRequest, stream: web::Payload| {
|
|
|
|
async move { ws::start(Ws, &req, stream) }
|
|
|
|
},
|
|
|
|
))
|
|
|
|
});
|
2019-03-18 06:02:03 +01:00
|
|
|
|
|
|
|
// client service
|
2019-12-15 17:45:38 +01:00
|
|
|
let mut framed = srv.ws().await.unwrap();
|
|
|
|
framed
|
|
|
|
.send(ws::Message::Text("text".to_string()))
|
|
|
|
.await
|
2019-03-18 06:02:03 +01:00
|
|
|
.unwrap();
|
|
|
|
|
2019-12-15 17:45:38 +01:00
|
|
|
let item = framed.next().await.unwrap().unwrap();
|
|
|
|
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
|
2019-03-18 06:02:03 +01:00
|
|
|
|
2019-12-15 17:45:38 +01:00
|
|
|
framed
|
|
|
|
.send(ws::Message::Binary("text".into()))
|
|
|
|
.await
|
2019-03-18 06:02:03 +01:00
|
|
|
.unwrap();
|
2019-12-15 17:45:38 +01:00
|
|
|
let item = framed.next().await.unwrap().unwrap();
|
|
|
|
assert_eq!(item, ws::Frame::Binary(Bytes::from_static(b"text").into()));
|
|
|
|
|
|
|
|
framed.send(ws::Message::Ping("text".into())).await.unwrap();
|
|
|
|
let item = framed.next().await.unwrap().unwrap();
|
|
|
|
assert_eq!(item, ws::Frame::Pong(Bytes::copy_from_slice(b"text")));
|
2019-03-18 06:02:03 +01:00
|
|
|
|
2019-12-15 17:45:38 +01:00
|
|
|
framed
|
|
|
|
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
|
|
|
|
.await
|
2019-03-18 06:02:03 +01:00
|
|
|
.unwrap();
|
|
|
|
|
2019-12-15 17:45:38 +01:00
|
|
|
let item = framed.next().await.unwrap().unwrap();
|
|
|
|
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
|
2019-03-18 06:02:03 +01:00
|
|
|
}
|