mirror of
https://github.com/actix/examples
synced 2025-06-28 09:50:36 +02:00
migrate readis and websockets examples
This commit is contained in:
@ -1,9 +1,8 @@
|
||||
[package]
|
||||
name = "websocket"
|
||||
version = "0.1.0"
|
||||
version = "2.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[[bin]]
|
||||
name = "websocket-server"
|
||||
@ -14,12 +13,13 @@ name = "websocket-client"
|
||||
path = "src/client.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.8.2"
|
||||
actix-codec = "0.1.2"
|
||||
actix-web = "1.0.0"
|
||||
actix-web-actors = "1.0.0"
|
||||
actix-files = "0.1.1"
|
||||
awc = "0.2.1"
|
||||
actix = "0.9.0-alpha.2"
|
||||
actix-codec = "0.2.0"
|
||||
actix-web = "2.0.0-alpha.6"
|
||||
actix-web-actors = "2.0.0-alpha.1"
|
||||
actix-files = "0.2.0-alpha.3"
|
||||
actix-rt = "1.0.0"
|
||||
awc = "1.0.0"
|
||||
env_logger = "0.6"
|
||||
futures = "0.1"
|
||||
bytes = "0.4"
|
||||
futures = "0.3.1"
|
||||
bytes = "0.5.3"
|
||||
|
@ -10,52 +10,47 @@ use awc::{
|
||||
ws::{Codec, Frame, Message},
|
||||
Client,
|
||||
};
|
||||
use futures::{
|
||||
lazy,
|
||||
stream::{SplitSink, Stream},
|
||||
Future,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{SplitSink, StreamExt};
|
||||
|
||||
fn main() {
|
||||
#[actix_rt::main]
|
||||
async fn main() {
|
||||
::std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
env_logger::init();
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
Arbiter::spawn(lazy(|| {
|
||||
Client::new()
|
||||
.ws("http://127.0.0.1:8080/ws/")
|
||||
.connect()
|
||||
.map_err(|e| {
|
||||
println!("Error: {}", e);
|
||||
})
|
||||
.map(|(response, framed)| {
|
||||
println!("{:?}", response);
|
||||
let (sink, stream) = framed.split();
|
||||
let addr = ChatClient::create(|ctx| {
|
||||
ChatClient::add_stream(stream, ctx);
|
||||
ChatClient(SinkWrite::new(sink, ctx))
|
||||
});
|
||||
let (response, framed) = Client::new()
|
||||
.ws("http://127.0.0.1:8080/ws/")
|
||||
.connect()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
println!("Error: {}", e);
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// start console loop
|
||||
thread::spawn(move || loop {
|
||||
let mut cmd = String::new();
|
||||
if io::stdin().read_line(&mut cmd).is_err() {
|
||||
println!("error");
|
||||
return;
|
||||
}
|
||||
addr.do_send(ClientCommand(cmd));
|
||||
});
|
||||
})
|
||||
}));
|
||||
println!("{:?}", response);
|
||||
let (sink, stream) = framed.split();
|
||||
let addr = ChatClient::create(|ctx| {
|
||||
ChatClient::add_stream(stream, ctx);
|
||||
ChatClient(SinkWrite::new(sink, ctx))
|
||||
});
|
||||
|
||||
let _ = sys.run();
|
||||
// start console loop
|
||||
thread::spawn(move || loop {
|
||||
let mut cmd = String::new();
|
||||
if io::stdin().read_line(&mut cmd).is_err() {
|
||||
println!("error");
|
||||
return;
|
||||
}
|
||||
addr.do_send(ClientCommand(cmd));
|
||||
});
|
||||
}
|
||||
|
||||
struct ChatClient<T>(SinkWrite<SplitSink<Framed<T, Codec>>>)
|
||||
struct ChatClient<T>(SinkWrite<Message, SplitSink<Framed<T, Codec>, Message>>)
|
||||
where
|
||||
T: AsyncRead + AsyncWrite;
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "()")]
|
||||
struct ClientCommand(String);
|
||||
|
||||
impl<T: 'static> Actor for ChatClient<T>
|
||||
@ -83,7 +78,7 @@ where
|
||||
{
|
||||
fn hb(&self, ctx: &mut Context<Self>) {
|
||||
ctx.run_later(Duration::new(1, 0), |act, ctx| {
|
||||
act.0.write(Message::Ping(String::new())).unwrap();
|
||||
act.0.write(Message::Ping(Bytes::from_static(b""))).unwrap();
|
||||
act.hb(ctx);
|
||||
|
||||
// client should also check for a timeout here, similar to the
|
||||
@ -105,12 +100,12 @@ where
|
||||
}
|
||||
|
||||
/// Handle server websocket messages
|
||||
impl<T: 'static> StreamHandler<Frame, WsProtocolError> for ChatClient<T>
|
||||
impl<T: 'static> StreamHandler<Result<Frame, WsProtocolError>> for ChatClient<T>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
{
|
||||
fn handle(&mut self, msg: Frame, _ctx: &mut Context<Self>) {
|
||||
if let Frame::Text(txt) = msg {
|
||||
fn handle(&mut self, msg: Result<Frame, WsProtocolError>, _: &mut Context<Self>) {
|
||||
if let Ok(Frame::Text(txt)) = msg {
|
||||
println!("Server: {:?}", txt)
|
||||
}
|
||||
}
|
||||
|
@ -16,10 +16,10 @@ const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// do websocket handshake and start `MyWebSocket` actor
|
||||
fn ws_index(r: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
|
||||
async fn ws_index(r: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
|
||||
println!("{:?}", r);
|
||||
let res = ws::start(MyWebSocket::new(), &r, stream);
|
||||
println!("{:?}", res.as_ref().unwrap());
|
||||
println!("{:?}", res);
|
||||
res
|
||||
}
|
||||
|
||||
@ -41,24 +41,28 @@ impl Actor for MyWebSocket {
|
||||
}
|
||||
|
||||
/// Handler for `ws::Message`
|
||||
impl StreamHandler<ws::Message, ws::ProtocolError> for MyWebSocket {
|
||||
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
|
||||
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWebSocket {
|
||||
fn handle(
|
||||
&mut self,
|
||||
msg: Result<ws::Message, ws::ProtocolError>,
|
||||
ctx: &mut Self::Context,
|
||||
) {
|
||||
// process websocket messages
|
||||
println!("WS: {:?}", msg);
|
||||
match msg {
|
||||
ws::Message::Ping(msg) => {
|
||||
Ok(ws::Message::Ping(msg)) => {
|
||||
self.hb = Instant::now();
|
||||
ctx.pong(&msg);
|
||||
}
|
||||
ws::Message::Pong(_) => {
|
||||
Ok(ws::Message::Pong(_)) => {
|
||||
self.hb = Instant::now();
|
||||
}
|
||||
ws::Message::Text(text) => ctx.text(text),
|
||||
ws::Message::Binary(bin) => ctx.binary(bin),
|
||||
ws::Message::Close(_) => {
|
||||
Ok(ws::Message::Text(text)) => ctx.text(text),
|
||||
Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
|
||||
Ok(ws::Message::Close(_)) => {
|
||||
ctx.stop();
|
||||
}
|
||||
ws::Message::Nop => (),
|
||||
_ => ctx.stop(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -85,12 +89,13 @@ impl MyWebSocket {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.ping("");
|
||||
ctx.ping(b"");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
#[actix_rt::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
|
||||
env_logger::init();
|
||||
|
||||
@ -105,5 +110,6 @@ fn main() -> std::io::Result<()> {
|
||||
})
|
||||
// start http server on 127.0.0.1:8080
|
||||
.bind("127.0.0.1:8080")?
|
||||
.run()
|
||||
.start()
|
||||
.await
|
||||
}
|
||||
|
Reference in New Issue
Block a user