2019-03-10 03:03:09 +01:00
|
|
|
use std::time::{Duration, Instant};
|
2018-05-11 23:35:43 +02:00
|
|
|
|
2019-03-29 23:08:35 +01:00
|
|
|
use actix::*;
|
|
|
|
use actix_files as fs;
|
|
|
|
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
|
|
|
|
use actix_web_actors::ws;
|
|
|
|
|
2018-05-11 23:35:43 +02:00
|
|
|
mod codec;
|
|
|
|
mod server;
|
|
|
|
mod session;
|
|
|
|
|
2018-09-27 21:37:19 +02:00
|
|
|
/// How often heartbeat pings are sent
|
|
|
|
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
|
|
|
/// How long before lack of client response causes a timeout
|
|
|
|
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
|
|
|
|
|
2018-05-11 23:35:43 +02:00
|
|
|
/// Entry point for our route
|
2019-12-16 08:09:54 +01:00
|
|
|
async fn chat_route(
|
2019-03-29 23:08:35 +01:00
|
|
|
req: HttpRequest,
|
|
|
|
stream: web::Payload,
|
|
|
|
srv: web::Data<Addr<server::ChatServer>>,
|
|
|
|
) -> Result<HttpResponse, Error> {
|
2018-05-11 23:35:43 +02:00
|
|
|
ws::start(
|
|
|
|
WsChatSession {
|
|
|
|
id: 0,
|
|
|
|
hb: Instant::now(),
|
|
|
|
room: "Main".to_owned(),
|
|
|
|
name: None,
|
2019-03-29 23:08:35 +01:00
|
|
|
addr: srv.get_ref().clone(),
|
2018-05-11 23:35:43 +02:00
|
|
|
},
|
2019-03-29 23:08:35 +01:00
|
|
|
&req,
|
|
|
|
stream,
|
2018-05-11 23:35:43 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
struct WsChatSession {
|
|
|
|
/// unique session id
|
|
|
|
id: usize,
|
2018-09-27 21:37:19 +02:00
|
|
|
/// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
|
|
|
|
/// otherwise we drop connection.
|
2018-05-11 23:35:43 +02:00
|
|
|
hb: Instant,
|
|
|
|
/// joined room
|
|
|
|
room: String,
|
|
|
|
/// peer name
|
|
|
|
name: Option<String>,
|
2019-03-29 23:08:35 +01:00
|
|
|
/// Chat server
|
|
|
|
addr: Addr<server::ChatServer>,
|
2018-05-11 23:35:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Actor for WsChatSession {
|
2019-03-29 23:08:35 +01:00
|
|
|
type Context = ws::WebsocketContext<Self>;
|
2018-05-11 23:35:43 +02:00
|
|
|
|
|
|
|
/// Method is called on actor start.
|
|
|
|
/// We register ws session with ChatServer
|
|
|
|
fn started(&mut self, ctx: &mut Self::Context) {
|
2019-03-29 23:08:35 +01:00
|
|
|
// we'll start heartbeat process on session start.
|
|
|
|
self.hb(ctx);
|
|
|
|
|
2018-05-11 23:35:43 +02:00
|
|
|
// register self in chat server. `AsyncContext::wait` register
|
|
|
|
// future within context, but context waits until this future resolves
|
|
|
|
// before processing any other events.
|
|
|
|
// HttpContext::state() is instance of WsChatSessionState, state is shared
|
|
|
|
// across all routes within application
|
2018-07-16 08:36:53 +02:00
|
|
|
let addr = ctx.address();
|
2019-03-29 23:08:35 +01:00
|
|
|
self.addr
|
2018-05-11 23:35:43 +02:00
|
|
|
.send(server::Connect {
|
|
|
|
addr: addr.recipient(),
|
|
|
|
})
|
|
|
|
.into_actor(self)
|
|
|
|
.then(|res, act, ctx| {
|
|
|
|
match res {
|
|
|
|
Ok(res) => act.id = res,
|
|
|
|
// something is wrong with chat server
|
|
|
|
_ => ctx.stop(),
|
|
|
|
}
|
2019-12-16 08:09:54 +01:00
|
|
|
fut::ready(())
|
2018-05-11 23:35:43 +02:00
|
|
|
})
|
|
|
|
.wait(ctx);
|
|
|
|
}
|
|
|
|
|
2019-03-29 23:08:35 +01:00
|
|
|
fn stopping(&mut self, _: &mut Self::Context) -> Running {
|
2018-05-11 23:35:43 +02:00
|
|
|
// notify chat server
|
2019-03-29 23:08:35 +01:00
|
|
|
self.addr.do_send(server::Disconnect { id: self.id });
|
2018-05-11 23:35:43 +02:00
|
|
|
Running::Stop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Handle messages from chat server, we simply send it to peer websocket
|
|
|
|
impl Handler<session::Message> for WsChatSession {
|
|
|
|
type Result = ();
|
|
|
|
|
|
|
|
fn handle(&mut self, msg: session::Message, ctx: &mut Self::Context) {
|
|
|
|
ctx.text(msg.0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// WebSocket message handler
|
2019-12-16 08:09:54 +01:00
|
|
|
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,
|
|
|
|
};
|
|
|
|
|
2018-05-11 23:35:43 +02:00
|
|
|
println!("WEBSOCKET MESSAGE: {:?}", msg);
|
|
|
|
match msg {
|
2018-09-27 21:37:19 +02:00
|
|
|
ws::Message::Ping(msg) => {
|
|
|
|
self.hb = Instant::now();
|
|
|
|
ctx.pong(&msg);
|
|
|
|
}
|
2018-09-30 22:09:00 +02:00
|
|
|
ws::Message::Pong(_) => {
|
|
|
|
self.hb = Instant::now();
|
|
|
|
}
|
2018-05-11 23:35:43 +02:00
|
|
|
ws::Message::Text(text) => {
|
|
|
|
let m = text.trim();
|
|
|
|
// we check for /sss type of messages
|
|
|
|
if m.starts_with('/') {
|
|
|
|
let v: Vec<&str> = m.splitn(2, ' ').collect();
|
|
|
|
match v[0] {
|
|
|
|
"/list" => {
|
|
|
|
// Send ListRooms message to chat server and wait for
|
|
|
|
// response
|
|
|
|
println!("List rooms");
|
2019-03-29 23:08:35 +01:00
|
|
|
self.addr
|
2018-05-11 23:35:43 +02:00
|
|
|
.send(server::ListRooms)
|
|
|
|
.into_actor(self)
|
|
|
|
.then(|res, _, ctx| {
|
|
|
|
match res {
|
|
|
|
Ok(rooms) => {
|
|
|
|
for room in rooms {
|
|
|
|
ctx.text(room);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => println!("Something is wrong"),
|
|
|
|
}
|
2019-12-16 08:09:54 +01:00
|
|
|
fut::ready(())
|
2018-05-11 23:35:43 +02:00
|
|
|
})
|
|
|
|
.wait(ctx)
|
|
|
|
// .wait(ctx) pauses all events in context,
|
|
|
|
// so actor wont receive any new messages until it get list
|
|
|
|
// of rooms back
|
|
|
|
}
|
|
|
|
"/join" => {
|
|
|
|
if v.len() == 2 {
|
|
|
|
self.room = v[1].to_owned();
|
2019-03-29 23:08:35 +01:00
|
|
|
self.addr.do_send(server::Join {
|
2018-05-11 23:35:43 +02:00
|
|
|
id: self.id,
|
|
|
|
name: self.room.clone(),
|
|
|
|
});
|
|
|
|
|
|
|
|
ctx.text("joined");
|
|
|
|
} else {
|
|
|
|
ctx.text("!!! room name is required");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"/name" => {
|
|
|
|
if v.len() == 2 {
|
|
|
|
self.name = Some(v[1].to_owned());
|
|
|
|
} else {
|
|
|
|
ctx.text("!!! name is required");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let msg = if let Some(ref name) = self.name {
|
|
|
|
format!("{}: {}", name, m)
|
|
|
|
} else {
|
|
|
|
m.to_owned()
|
|
|
|
};
|
|
|
|
// send message to chat server
|
2019-03-29 23:08:35 +01:00
|
|
|
self.addr.do_send(server::Message {
|
2018-05-11 23:35:43 +02:00
|
|
|
id: self.id,
|
2019-09-04 17:04:57 +02:00
|
|
|
msg,
|
2018-05-11 23:35:43 +02:00
|
|
|
room: self.room.clone(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2019-03-29 23:08:35 +01:00
|
|
|
ws::Message::Binary(_) => println!("Unexpected binary"),
|
2020-06-25 06:20:27 +02:00
|
|
|
ws::Message::Close(reason) => {
|
|
|
|
ctx.close(reason);
|
2018-05-11 23:35:43 +02:00
|
|
|
ctx.stop();
|
2019-03-10 03:03:09 +01:00
|
|
|
}
|
2019-12-16 08:09:54 +01:00
|
|
|
_ => (),
|
2018-05-11 23:35:43 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-28 09:53:51 +02:00
|
|
|
impl WsChatSession {
|
|
|
|
/// helper method that sends ping to client every second.
|
|
|
|
///
|
2018-09-27 21:37:19 +02:00
|
|
|
/// also this method checks heartbeats from client
|
2019-03-29 23:08:35 +01:00
|
|
|
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
|
2018-09-27 21:37:19 +02:00
|
|
|
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
|
2018-08-28 09:53:51 +02:00
|
|
|
// check client heartbeats
|
2018-09-27 21:37:19 +02:00
|
|
|
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
|
2018-08-28 09:53:51 +02:00
|
|
|
// heartbeat timed out
|
|
|
|
println!("Websocket Client heartbeat failed, disconnecting!");
|
|
|
|
|
|
|
|
// notify chat server
|
2019-03-29 23:08:35 +01:00
|
|
|
act.addr.do_send(server::Disconnect { id: act.id });
|
2018-08-28 09:53:51 +02:00
|
|
|
|
|
|
|
// stop actor
|
|
|
|
ctx.stop();
|
2018-09-27 21:37:19 +02:00
|
|
|
|
|
|
|
// don't try to send a ping
|
|
|
|
return;
|
2018-08-28 09:53:51 +02:00
|
|
|
}
|
|
|
|
|
2019-12-16 08:09:54 +01:00
|
|
|
ctx.ping(b"");
|
2018-08-28 09:53:51 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-12 17:49:45 +02:00
|
|
|
#[actix_web::main]
|
2019-12-16 08:09:54 +01:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2019-09-04 17:04:57 +02:00
|
|
|
env_logger::init();
|
2018-05-11 23:35:43 +02:00
|
|
|
|
2019-03-29 23:08:35 +01:00
|
|
|
// Start chat server actor
|
|
|
|
let server = server::ChatServer::default().start();
|
2018-05-11 23:35:43 +02:00
|
|
|
|
|
|
|
// Start tcp server in separate thread
|
|
|
|
let srv = server.clone();
|
2020-01-27 15:17:14 +01:00
|
|
|
session::tcp_server("127.0.0.1:12345", srv);
|
2018-05-11 23:35:43 +02:00
|
|
|
|
2019-12-16 08:09:54 +01:00
|
|
|
println!("Started http server: 127.0.0.1:8080");
|
|
|
|
|
2018-05-11 23:35:43 +02:00
|
|
|
// Create Http server with websocket support
|
|
|
|
HttpServer::new(move || {
|
2019-03-29 23:08:35 +01:00
|
|
|
App::new()
|
|
|
|
.data(server.clone())
|
2018-08-28 09:53:51 +02:00
|
|
|
// redirect to websocket.html
|
2019-03-29 23:08:35 +01:00
|
|
|
.service(web::resource("/").route(web::get().to(|| {
|
|
|
|
HttpResponse::Found()
|
|
|
|
.header("LOCATION", "/static/websocket.html")
|
|
|
|
.finish()
|
|
|
|
})))
|
2018-08-28 09:53:51 +02:00
|
|
|
// websocket
|
2019-03-29 23:08:35 +01:00
|
|
|
.service(web::resource("/ws/").to(chat_route))
|
2018-08-28 09:53:51 +02:00
|
|
|
// static resources
|
2019-03-29 23:08:35 +01:00
|
|
|
.service(fs::Files::new("/static/", "static/"))
|
2019-03-10 03:03:09 +01:00
|
|
|
})
|
2019-03-29 23:08:35 +01:00
|
|
|
.bind("127.0.0.1:8080")?
|
2019-12-25 17:48:33 +01:00
|
|
|
.run()
|
2019-12-16 08:09:54 +01:00
|
|
|
.await
|
2018-05-11 23:35:43 +02:00
|
|
|
}
|