Skip to content

Commit

Permalink
export ws module
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed Mar 18, 2019
1 parent fd3e351 commit 6ab7665
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 36 deletions.
7 changes: 1 addition & 6 deletions actix-web-actors/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
//! Actix actors integration for Actix web framework
mod context;
mod ws;
pub mod ws;

pub use self::context::HttpContext;
pub use self::ws::{ws_handshake, ws_start, WebsocketContext};

pub use actix_http::ws::CloseCode as WsCloseCode;
pub use actix_http::ws::ProtocolError as WsProtocolError;
pub use actix_http::ws::{Frame as WsFrame, Message as WsMessage};
17 changes: 8 additions & 9 deletions actix-web-actors/src/ws.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Websocket integration
use std::collections::VecDeque;
use std::io;

Expand All @@ -11,9 +12,11 @@ use actix::{
Message as ActixMessage, SpawnHandle,
};
use actix_codec::{Decoder, Encoder};
use actix_http::ws::{
hash_key, CloseReason, Codec, Frame, HandshakeError, Message, ProtocolError,
use actix_http::ws::hash_key;
pub use actix_http::ws::{
CloseCode, CloseReason, Codec, Frame, HandshakeError, Message, ProtocolError,
};

use actix_web::dev::{Head, HttpResponseBuilder};
use actix_web::error::{Error, ErrorInternalServerError, PayloadError};
use actix_web::http::{header, Method, StatusCode};
Expand All @@ -23,16 +26,12 @@ use futures::sync::oneshot::Sender;
use futures::{Async, Future, Poll, Stream};

/// Do websocket handshake and start ws actor.
pub fn ws_start<A, T>(
actor: A,
req: &HttpRequest,
stream: T,
) -> Result<HttpResponse, Error>
pub fn start<A, T>(actor: A, req: &HttpRequest, stream: T) -> Result<HttpResponse, Error>
where
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Frame, ProtocolError>,
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
{
let mut res = ws_handshake(req)?;
let mut res = handshake(req)?;
Ok(res.streaming(WebsocketContext::create(actor, stream)))
}

Expand All @@ -44,7 +43,7 @@ where
// /// `protocols` is a sequence of known protocols. On successful handshake,
// /// the returned response headers contain the first protocol in this list
// /// which the server also knows.
pub fn ws_handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> {
pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> {
// WebSocket accepts only GET
if *req.method() != Method::GET {
return Err(HandshakeError::GetMethodRequired);
Expand Down
44 changes: 23 additions & 21 deletions actix-web-actors/tests/test_ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,59 +9,61 @@ use futures::{Sink, Stream};
struct Ws;

impl Actor for Ws {
type Context = WebsocketContext<Self>;
type Context = ws::WebsocketContext<Self>;
}

impl StreamHandler<WsFrame, WsProtocolError> for Ws {
fn handle(&mut self, msg: WsFrame, ctx: &mut Self::Context) {
impl StreamHandler<ws::Frame, ws::ProtocolError> for Ws {
fn handle(&mut self, msg: ws::Frame, ctx: &mut Self::Context) {
match msg {
WsFrame::Ping(msg) => ctx.pong(&msg),
WsFrame::Text(text) => {
ws::Frame::Ping(msg) => ctx.pong(&msg),
ws::Frame::Text(text) => {
ctx.text(String::from_utf8_lossy(&text.unwrap())).to_owned()
}
WsFrame::Binary(bin) => ctx.binary(bin.unwrap()),
WsFrame::Close(reason) => ctx.close(reason),
ws::Frame::Binary(bin) => ctx.binary(bin.unwrap()),
ws::Frame::Close(reason) => ctx.close(reason),
_ => (),
}
}
}

#[test]
fn test_simple() {
let mut srv =
TestServer::new(|| {
HttpService::new(App::new().service(web::resource("/").to(
|req: HttpRequest, stream: web::Payload<_>| ws_start(Ws, &req, stream),
)))
});
let mut srv = TestServer::new(|| {
HttpService::new(App::new().service(web::resource("/").to(
|req: HttpRequest, stream: web::Payload<_>| ws::start(Ws, &req, stream),
)))
});

// client service
let framed = srv.ws().unwrap();
let framed = srv
.block_on(framed.send(WsMessage::Text("text".to_string())))
.block_on(framed.send(ws::Message::Text("text".to_string())))
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(item, Some(WsFrame::Text(Some(BytesMut::from("text")))));
assert_eq!(item, Some(ws::Frame::Text(Some(BytesMut::from("text")))));

let framed = srv
.block_on(framed.send(WsMessage::Binary("text".into())))
.block_on(framed.send(ws::Message::Binary("text".into())))
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(
item,
Some(WsFrame::Binary(Some(Bytes::from_static(b"text").into())))
Some(ws::Frame::Binary(Some(Bytes::from_static(b"text").into())))
);

let framed = srv
.block_on(framed.send(WsMessage::Ping("text".into())))
.block_on(framed.send(ws::Message::Ping("text".into())))
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(item, Some(WsFrame::Pong("text".to_string().into())));
assert_eq!(item, Some(ws::Frame::Pong("text".to_string().into())));

let framed = srv
.block_on(framed.send(WsMessage::Close(Some(WsCloseCode::Normal.into()))))
.block_on(framed.send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))))
.unwrap();

let (item, _framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(item, Some(WsFrame::Close(Some(WsCloseCode::Normal.into()))));
assert_eq!(
item,
Some(ws::Frame::Close(Some(ws::CloseCode::Normal.into())))
);
}

0 comments on commit 6ab7665

Please sign in to comment.