1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-18 22:01:50 +01:00

211 lines
7.1 KiB
Rust
Raw Normal View History

2017-10-20 17:16:17 -07:00
#![allow(unused_variables)]
extern crate rand;
extern crate bytes;
extern crate byteorder;
2017-10-21 15:21:16 -07:00
extern crate futures;
2017-10-20 17:16:17 -07:00
extern crate tokio_io;
extern crate tokio_core;
2017-10-20 23:12:36 -07:00
extern crate env_logger;
2017-10-20 17:16:17 -07:00
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
2018-01-05 14:01:19 -08:00
#[macro_use]
2017-10-06 21:48:14 -07:00
extern crate actix;
2017-10-14 07:59:35 -07:00
extern crate actix_web;
2017-10-20 17:16:17 -07:00
use std::time::Instant;
2017-10-06 21:48:14 -07:00
2017-10-15 15:10:35 -07:00
use actix::*;
2017-10-14 07:59:35 -07:00
use actix_web::*;
2017-10-06 21:48:14 -07:00
2017-10-20 17:16:17 -07:00
mod codec;
mod server;
mod session;
2017-10-06 21:48:14 -07:00
2017-10-20 17:16:17 -07:00
/// This is our websocket route state, this state is shared with all route instances
/// via `HttpContext::state()`
struct WsChatSessionState {
addr: SyncAddress<server::ChatServer>,
2017-10-06 21:48:14 -07:00
}
2017-11-29 14:03:18 -08:00
/// Entry point for our route
2017-12-31 21:55:25 -08:00
fn chat_route(req: HttpRequest<WsChatSessionState>) -> Result<HttpResponse> {
2017-11-29 14:03:18 -08:00
ws::start(
req,
WsChatSession {
id: 0,
hb: Instant::now(),
room: "Main".to_owned(),
name: None})
}
2017-10-20 17:16:17 -07:00
struct WsChatSession {
/// unique session id
id: usize,
/// Client must send ping at least once per 10 seconds, otherwise we drop connection.
hb: Instant,
/// joined room
room: String,
/// peer name
name: Option<String>,
2017-10-06 21:48:14 -07:00
}
2017-10-20 17:16:17 -07:00
impl Actor for WsChatSession {
2018-01-10 10:40:14 -08:00
type Context = ws::WebsocketContext<Self, WsChatSessionState>;
2018-01-06 01:06:35 -08:00
/// Method is called on actor start.
/// We register ws session with ChatServer
fn started(&mut self, ctx: &mut Self::Context) {
// 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
let subs = ctx.sync_subscriber();
ctx.state().addr.call(
self, server::Connect{addr: subs}).then(
|res, act, ctx| {
match res {
Ok(Ok(res)) => act.id = res,
// something is wrong with chat server
_ => ctx.stop(),
}
fut::ok(())
}).wait(ctx);
}
2018-01-06 23:22:10 -08:00
fn stopping(&mut self, ctx: &mut Self::Context) -> bool {
2018-01-06 01:06:35 -08:00
// notify chat server
ctx.state().addr.send(server::Disconnect{id: self.id});
2018-01-06 23:22:10 -08:00
true
2018-01-06 01:06:35 -08:00
}
2017-10-07 21:48:00 -07:00
}
2017-10-20 17:16:17 -07:00
/// Handle messages from chat server, we simply send it to peer websocket
impl Handler<session::Message> for WsChatSession {
2018-01-05 14:01:19 -08:00
type Result = ();
fn handle(&mut self, msg: session::Message, ctx: &mut Self::Context) {
2018-01-10 10:40:14 -08:00
ctx.text(&msg.0);
2017-10-20 17:16:17 -07:00
}
}
/// WebSocket message handler
impl Handler<ws::Message> for WsChatSession {
2018-01-05 14:01:19 -08:00
type Result = ();
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
2017-10-20 17:16:17 -07:00
println!("WEBSOCKET MESSAGE: {:?}", msg);
2017-10-07 21:48:00 -07:00
match msg {
2018-01-10 10:40:14 -08:00
ws::Message::Ping(msg) => ctx.pong(&msg),
ws::Message::Pong(msg) => self.hb = Instant::now(),
2017-10-20 17:16:17 -07: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");
ctx.state().addr.call(self, server::ListRooms).then(|res, _, ctx| {
match res {
Ok(Ok(rooms)) => {
for room in rooms {
2018-01-10 10:40:14 -08:00
ctx.text(&room);
2017-10-20 17:16:17 -07:00
}
},
_ => println!("Something is wrong"),
}
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
},
"/join" => {
if v.len() == 2 {
self.room = v[1].to_owned();
ctx.state().addr.send(
server::Join{id: self.id, name: self.room.clone()});
2018-01-10 10:40:14 -08:00
ctx.text("joined");
2017-10-20 17:16:17 -07:00
} else {
2018-01-10 10:40:14 -08:00
ctx.text("!!! room name is required");
2017-10-20 17:16:17 -07:00
}
},
"/name" => {
if v.len() == 2 {
self.name = Some(v[1].to_owned());
} else {
2018-01-10 10:40:14 -08:00
ctx.text("!!! name is required");
2017-10-20 17:16:17 -07:00
}
},
2018-01-10 10:40:14 -08:00
_ => ctx.text(&format!("!!! unknown command: {:?}", m)),
2017-10-20 17:16:17 -07:00
}
} else {
let msg = if let Some(ref name) = self.name {
format!("{}: {}", name, m)
} else {
m.to_owned()
};
// send message to chat server
ctx.state().addr.send(
server::Message{id: self.id,
msg: msg,
room: self.room.clone()})
}
},
ws::Message::Binary(bin) =>
println!("Unexpected binary"),
2017-10-13 16:33:23 -07:00
ws::Message::Closed | ws::Message::Error => {
ctx.stop();
}
2017-10-07 21:48:00 -07:00
_ => (),
}
}
}
2017-10-06 21:48:14 -07:00
fn main() {
2017-10-20 23:12:36 -07:00
let _ = env_logger::init();
2017-10-20 17:16:17 -07:00
let sys = actix::System::new("websocket-example");
2017-10-21 02:08:07 -07:00
// Start chat server actor in separate thread
let server: SyncAddress<_> =
Arbiter::start(|_| server::ChatServer::default());
// Start tcp server in separate thread
let srv = server.clone();
Arbiter::new("tcp-server").send::<msgs::Execute>(
msgs::Execute::new(move || {
session::TcpServer::new("127.0.0.1:12345", srv);
Ok(())
}));
2017-10-06 21:48:14 -07:00
2017-10-20 17:16:17 -07:00
// Create Http server with websocket support
2017-12-30 16:50:49 +01:00
let addr = HttpServer::new(
2017-12-13 17:28:16 -08:00
move || {
// Websocket sessions state
let state = WsChatSessionState { addr: server.clone() };
Application::with_state(state)
2017-12-20 16:32:31 -08:00
// redirect to websocket.html
.resource("/", |r| r.method(Method::GET).f(|_| {
2017-12-13 17:28:16 -08:00
httpcodes::HTTPFound
.build()
.header("LOCATION", "/static/websocket.html")
2017-12-20 16:32:31 -08:00
.finish()
2017-12-13 17:28:16 -08:00
}))
2017-12-18 13:06:41 -08:00
// websocket
2017-12-13 17:28:16 -08:00
.resource("/ws/", |r| r.route().f(chat_route))
2017-12-18 13:06:41 -08:00
// static resources
2018-01-02 15:52:11 -08:00
.handler("/static/", fs::StaticFiles::new("static/", true))
2017-12-13 17:28:16 -08:00
})
2017-12-18 13:06:41 -08:00
.bind("127.0.0.1:8080").unwrap()
2017-12-19 09:08:36 -08:00
.start();
2017-10-06 21:48:14 -07:00
2017-12-30 16:50:49 +01:00
println!("Started http server: 127.0.0.1:8080");
2017-10-06 21:48:14 -07:00
let _ = sys.run();
}