1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/examples/websocket-chat/src/session.rs

205 lines
7.1 KiB
Rust
Raw Normal View History

2017-10-21 02:16:17 +02:00
//! `ClientSession` is an actor, it manages peer tcp connection and
//! proxies commands from peer to `ChatServer`.
2018-02-08 23:03:27 +01:00
use std::{io, net};
2017-10-21 02:16:17 +02:00
use std::str::FromStr;
use std::time::{Instant, Duration};
2017-10-22 00:21:16 +02:00
use futures::Stream;
2018-01-28 10:04:58 +01:00
use tokio_io::AsyncRead;
2018-02-08 23:03:27 +01:00
use tokio_io::io::WriteHalf;
use tokio_io::codec::FramedRead;
2017-10-21 02:16:17 +02:00
use tokio_core::net::{TcpStream, TcpListener};
2018-01-05 23:01:19 +01:00
use actix::prelude::*;
2017-10-21 02:16:17 +02:00
use server::{self, ChatServer};
use codec::{ChatRequest, ChatResponse, ChatCodec};
/// Chat server sends this messages to session
2018-01-05 23:01:19 +01:00
#[derive(Message)]
2017-10-21 02:16:17 +02:00
pub struct Message(pub String);
2018-01-16 19:59:33 +01:00
/// `ChatSession` actor is responsible for tcp peer communications.
2017-10-21 02:16:17 +02:00
pub struct ChatSession {
/// unique session id
id: usize,
/// this is address of chat server
addr: SyncAddress<ChatServer>,
/// Client must send ping at least once per 10 seconds, otherwise we drop connection.
hb: Instant,
/// joined room
room: String,
2018-01-28 10:04:58 +01:00
/// Framed wrapper
2018-02-08 23:03:27 +01:00
framed: actix::io::FramedWrite<WriteHalf<TcpStream>, ChatCodec>,
2017-10-21 02:16:17 +02:00
}
impl Actor for ChatSession {
/// For tcp communication we are going to use `FramedContext`.
2018-01-16 19:59:33 +01:00
/// It is convenient wrapper around `Framed` object from `tokio_io`
2018-01-28 10:04:58 +01:00
type Context = Context<Self>;
2017-10-21 02:16:17 +02:00
2018-01-05 23:01:19 +01:00
fn started(&mut self, ctx: &mut Self::Context) {
2017-10-21 02:16:17 +02:00
// we'll start heartbeat process on session start.
self.hb(ctx);
// register self in chat server. `AsyncContext::wait` register
// future within context, but context waits until this future resolves
// before processing any other events.
2018-01-05 23:01:19 +01:00
let addr: SyncAddress<_> = ctx.address();
2018-02-09 05:55:34 +01:00
self.addr.call(self, server::Connect{addr: addr.into()})
2018-01-05 23:01:19 +01:00
.then(|res, act, ctx| {
match res {
Ok(Ok(res)) => act.id = res,
// something is wrong with chat server
_ => ctx.stop(),
}
actix::fut::ok(())
}).wait(ctx);
2017-10-21 02:16:17 +02:00
}
2018-01-07 08:22:10 +01:00
fn stopping(&mut self, ctx: &mut Self::Context) -> bool {
2017-10-21 02:16:17 +02:00
// notify chat server
self.addr.send(server::Disconnect{id: self.id});
2018-01-07 08:22:10 +01:00
true
2017-10-21 02:16:17 +02:00
}
}
2018-02-08 23:03:27 +01:00
impl actix::io::WriteHandler<io::Error> for ChatSession {}
2018-01-28 10:04:58 +01:00
/// To use `Framed` we have to define Io type and Codec
2018-02-08 23:03:27 +01:00
impl StreamHandler<ChatRequest, io::Error> for ChatSession {
2017-10-21 02:16:17 +02:00
/// This is main event loop for client requests
2018-02-03 17:25:31 +01:00
fn handle(&mut self, msg: ChatRequest, ctx: &mut Context<Self>) {
2017-10-21 02:16:17 +02:00
match msg {
2018-02-03 17:25:31 +01:00
ChatRequest::List => {
// Send ListRooms message to chat server and wait for response
println!("List rooms");
self.addr.call(self, server::ListRooms).then(|res, act, ctx| {
match res {
Ok(Ok(rooms)) => {
2018-02-08 23:03:27 +01:00
act.framed.write(ChatResponse::Rooms(rooms));
2018-02-03 17:25:31 +01:00
},
2017-10-21 02:16:17 +02:00
_ => println!("Something is wrong"),
2018-02-03 17:25:31 +01:00
}
actix::fut::ok(())
}).wait(ctx)
// .wait(ctx) pauses all events in context,
// so actor wont receive any new messages until it get list of rooms back
},
ChatRequest::Join(name) => {
println!("Join to room: {}", name);
self.room = name.clone();
self.addr.send(server::Join{id: self.id, name: name.clone()});
2018-02-08 23:03:27 +01:00
self.framed.write(ChatResponse::Joined(name));
2018-02-03 17:25:31 +01:00
},
ChatRequest::Message(message) => {
// send message to chat server
println!("Peer message: {}", message);
self.addr.send(
server::Message{id: self.id,
msg: message, room:
self.room.clone()})
2017-10-21 02:16:17 +02:00
}
2018-02-03 17:25:31 +01:00
// we update heartbeat time on ping from peer
ChatRequest::Ping =>
self.hb = Instant::now(),
2017-10-21 02:16:17 +02:00
}
}
}
/// Handler for Message, chat server sends this message, we just send string to peer
impl Handler<Message> for ChatSession {
2018-01-05 23:01:19 +01:00
type Result = ();
2017-10-21 02:16:17 +02:00
2018-01-28 10:04:58 +01:00
fn handle(&mut self, msg: Message, ctx: &mut Context<Self>) {
2017-10-21 02:16:17 +02:00
// send message to peer
2018-02-08 23:03:27 +01:00
self.framed.write(ChatResponse::Message(msg.0));
2017-10-21 02:16:17 +02:00
}
}
/// Helper methods
impl ChatSession {
2018-01-28 10:04:58 +01:00
pub fn new(addr: SyncAddress<ChatServer>,
2018-02-08 23:03:27 +01:00
framed: actix::io::FramedWrite<WriteHalf<TcpStream>, ChatCodec>) -> ChatSession {
2018-01-28 10:04:58 +01:00
ChatSession {id: 0, addr: addr, hb: Instant::now(),
room: "Main".to_owned(), framed: framed}
2017-10-21 02:16:17 +02:00
}
/// helper method that sends ping to client every second.
///
/// also this method check heartbeats from client
2018-01-28 10:04:58 +01:00
fn hb(&self, ctx: &mut Context<Self>) {
2017-10-21 02:16:17 +02:00
ctx.run_later(Duration::new(1, 0), |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > Duration::new(10, 0) {
// heartbeat timed out
println!("Client heartbeat failed, disconnecting!");
// notify chat server
act.addr.send(server::Disconnect{id: act.id});
// stop actor
ctx.stop();
}
2018-02-08 23:03:27 +01:00
act.framed.write(ChatResponse::Ping);
2018-01-28 10:04:58 +01:00
// if we can not send message to sink, sink is closed (disconnected)
act.hb(ctx);
2017-10-21 02:16:17 +02:00
});
}
}
2018-01-16 19:59:33 +01:00
/// Define tcp server that will accept incoming tcp connection and create
2017-10-21 02:16:17 +02:00
/// chat actors.
pub struct TcpServer {
chat: SyncAddress<ChatServer>,
}
impl TcpServer {
pub fn new(s: &str, chat: SyncAddress<ChatServer>) {
// Create server listener
let addr = net::SocketAddr::from_str("127.0.0.1:12345").unwrap();
let listener = TcpListener::bind(&addr, Arbiter::handle()).unwrap();
// Our chat server `Server` is an actor, first we need to start it
// and then add stream on incoming tcp connections to it.
// TcpListener::incoming() returns stream of the (TcpStream, net::SocketAddr) items
// So to be able to handle this events `Server` actor has to implement
// stream handler `StreamHandler<(TcpStream, net::SocketAddr), io::Error>`
let _: () = TcpServer::create(|ctx| {
2018-01-05 23:01:19 +01:00
ctx.add_message_stream(listener.incoming()
.map_err(|_| ())
.map(|(t, a)| TcpConnect(t, a)));
2017-10-21 02:16:17 +02:00
TcpServer{chat: chat}
});
}
}
/// Make actor from `Server`
impl Actor for TcpServer {
/// Every actor has to provide execution `Context` in which it can run.
type Context = Context<Self>;
}
2018-01-05 23:01:19 +01:00
#[derive(Message)]
2017-10-22 00:21:16 +02:00
struct TcpConnect(TcpStream, net::SocketAddr);
2017-10-21 02:16:17 +02:00
2017-10-22 00:21:16 +02:00
/// Handle stream of TcpStream's
2018-01-05 23:01:19 +01:00
impl Handler<TcpConnect> for TcpServer {
type Result = ();
2017-10-21 02:16:17 +02:00
2018-01-05 23:01:19 +01:00
fn handle(&mut self, msg: TcpConnect, _: &mut Context<Self>) {
2017-10-21 02:16:17 +02:00
// For each incoming connection we create `ChatSession` actor
// with out chat server address.
let server = self.chat.clone();
2018-02-08 23:03:27 +01:00
let _: () = ChatSession::create(|ctx| {
let (r, w) = msg.0.split();
ChatSession::add_stream(FramedRead::new(r, ChatCodec), ctx);
ChatSession::new(server, actix::io::FramedWrite::new(w, ChatCodec, ctx))
2018-01-28 10:04:58 +01:00
});
2017-10-21 02:16:17 +02:00
}
}