1
0
mirror of https://github.com/actix/examples synced 2025-06-28 18:00:37 +02:00

migrate websocket-chat example

This commit is contained in:
Nikolay Kim
2019-12-15 22:55:54 +06:00
parent 5ffbaacdce
commit e166c66f0b
5 changed files with 42 additions and 25 deletions

View File

@ -13,7 +13,7 @@ const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// Entry point for our route
fn chat_route(
async fn chat_route(
req: HttpRequest,
stream: web::Payload,
srv: web::Data<Addr<server::ChatServer>>,
@ -71,7 +71,7 @@ impl Actor for WsChatSession {
// something is wrong with chat server
_ => ctx.stop(),
}
fut::ok(())
fut::ready(())
})
.wait(ctx);
}
@ -93,8 +93,20 @@ impl Handler<server::Message> for WsChatSession {
}
/// WebSocket message handler
impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
fn handle(
&mut self,
msg: Result<ws::Message, ws::ProtocolError>,
ctx: &mut Self::Context,
) {
let msg = match msg {
Err(_) => {
ctx.stop();
return;
}
Ok(msg) => msg,
};
println!("WEBSOCKET MESSAGE: {:?}", msg);
match msg {
ws::Message::Ping(msg) => {
@ -126,7 +138,7 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
}
_ => println!("Something is wrong"),
}
fut::ok(())
fut::ready(())
})
.wait(ctx)
// .wait(ctx) pauses all events in context,
@ -173,6 +185,9 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
ws::Message::Close(_) => {
ctx.stop();
}
ws::Message::Continuation(_) => {
ctx.stop();
}
ws::Message::Nop => (),
}
}
@ -199,14 +214,14 @@ impl WsChatSession {
return;
}
ctx.ping("");
ctx.ping(b"");
});
}
}
fn main() -> std::io::Result<()> {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
let sys = System::new("ws-example");
// Start chat server actor
let server = server::ChatServer::default().start();
@ -227,7 +242,6 @@ fn main() -> std::io::Result<()> {
.service(fs::Files::new("/static/", "static/"))
})
.bind("127.0.0.1:8080")?
.start();
sys.run()
.start()
.await
}

View File

@ -8,6 +8,7 @@ use std::collections::{HashMap, HashSet};
/// Chat server sends this messages to session
#[derive(Message)]
#[rtype(result = "()")]
pub struct Message(pub String);
/// Message for chat server communications
@ -21,12 +22,14 @@ pub struct Connect {
/// Session is disconnected
#[derive(Message)]
#[rtype(result = "()")]
pub struct Disconnect {
pub id: usize,
}
/// Send message to specific room
#[derive(Message)]
#[rtype(result = "()")]
pub struct ClientMessage {
/// Id of the client session
pub id: usize,
@ -45,6 +48,7 @@ impl actix::Message for ListRooms {
/// Join room, if room does not exists create new one.
#[derive(Message)]
#[rtype(result = "()")]
pub struct Join {
/// Client id
pub id: usize,