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

WebSocket Chat example using actix-broker (#44)

WebSocket Chat Example rewrite with actix-broker
This commit is contained in:
Christopher Ricketts
2018-09-18 11:19:45 +01:00
committed by Douman
parent 6b68cfc529
commit 8edf86e4b8
8 changed files with 511 additions and 0 deletions

View File

@ -0,0 +1,167 @@
#[macro_use]
extern crate actix;
extern crate actix_broker;
extern crate actix_web;
extern crate futures;
extern crate rand;
#[macro_use]
extern crate log;
extern crate simple_logger;
use actix::fut;
use actix::prelude::*;
use actix_broker::BrokerIssue;
use actix_web::server::HttpServer;
use actix_web::{fs, ws, App, Error, HttpRequest, HttpResponse};
mod server;
use server::*;
fn chat_route(req: &HttpRequest<()>) -> Result<HttpResponse, Error> {
ws::start(req, WsChatSession::default())
}
#[derive(Default)]
struct WsChatSession {
id: usize,
room: String,
name: Option<String>,
}
impl WsChatSession {
fn join_room(&mut self, room_name: &str, ctx: &mut ws::WebsocketContext<Self>) {
let room_name = room_name.to_owned();
// First send a leave message for the current room
let leave_msg = LeaveRoom(self.room.clone(), self.id);
// issue_sync comes from having the `BrokerIssue` trait in scope.
self.issue_sync(leave_msg, ctx);
// Then send a join message for the new room
let join_msg = JoinRoom(
room_name.to_owned(),
self.name.clone(),
ctx.address().recipient(),
);
WsChatServer::from_registry()
.send(join_msg)
.into_actor(self)
.then(|id, act, _ctx| {
if let Ok(id) = id {
act.id = id;
act.room = room_name;
}
fut::ok(())
}).spawn(ctx);
}
fn list_rooms(&mut self, ctx: &mut ws::WebsocketContext<Self>) {
WsChatServer::from_registry()
.send(ListRooms)
.into_actor(self)
.then(|res, _, ctx| {
if let Ok(rooms) = res {
for room in rooms {
ctx.text(room);
}
}
fut::ok(())
}).spawn(ctx);
}
fn send_msg(&self, msg: &str) {
let content = format!(
"{}: {}",
self.name.clone().unwrap_or("anon".to_string()),
msg
);
let msg = SendMessage(self.room.clone(), self.id, content);
// issue_async comes from having the `BrokerIssue` trait in scope.
self.issue_async(msg);
}
}
impl Actor for WsChatSession {
type Context = ws::WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.join_room("Main", ctx);
}
fn stopped(&mut self, _ctx: &mut Self::Context) {
info!(
"WsChatSession closed for {}({}) in room {}",
self.name.clone().unwrap_or("anon".to_string()),
self.id,
self.room
);
}
}
impl Handler<ChatMessage> for WsChatSession {
type Result = ();
fn handle(&mut self, msg: ChatMessage, ctx: &mut Self::Context) {
ctx.text(msg.0);
}
}
impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
debug!("WEBSOCKET MESSAGE: {:?}", msg);
match msg {
ws::Message::Text(text) => {
let msg = text.trim();
if msg.starts_with('/') {
let mut command = msg.splitn(2, ' ');
match command.next() {
Some("/list") => self.list_rooms(ctx),
Some("/join") => {
if let Some(room_name) = command.next() {
self.join_room(room_name, ctx);
} else {
ctx.text("!!! room name is required");
}
}
Some("/name") => {
if let Some(name) = command.next() {
self.name = Some(name.to_owned());
ctx.text(format!("name changed to: {}", name));
} else {
ctx.text("!!! name is required");
}
}
_ => ctx.text(format!("!!! unknown command: {:?}", msg)),
}
return;
}
self.send_msg(msg);
}
ws::Message::Close(_) => {
ctx.stop();
}
_ => {}
}
}
}
fn main() {
let sys = actix::System::new("websocket-broker-example");
simple_logger::init_with_level(log::Level::Info).unwrap();
HttpServer::new(move || {
App::new()
.resource("/ws/", |r| r.route().f(chat_route))
.handler(
"/",
fs::StaticFiles::new("./static/")
.unwrap()
.index_file("index.html"),
)
}).bind("127.0.0.1:8080")
.unwrap()
.start();
info!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}

View File

@ -0,0 +1,133 @@
use actix::prelude::*;
use actix_broker::BrokerSubscribe;
use rand;
use std::collections::HashMap;
use std::mem;
#[derive(Clone, Message)]
pub struct ChatMessage(pub String);
#[derive(Clone, Message)]
#[rtype(result = "usize")]
pub struct JoinRoom(pub String, pub Option<String>, pub Recipient<ChatMessage>);
#[derive(Clone, Message)]
pub struct LeaveRoom(pub String, pub usize);
#[derive(Clone, Message)]
#[rtype(result = "Vec<String>")]
pub struct ListRooms;
#[derive(Clone, Message)]
pub struct SendMessage(pub String, pub usize, pub String);
type Client = Recipient<ChatMessage>;
type Room = HashMap<usize, Client>;
#[derive(Default)]
pub struct WsChatServer {
rooms: HashMap<String, Room>,
}
impl WsChatServer {
fn take_room(&mut self, room_name: &str) -> Option<Room> {
let room = self.rooms.get_mut(room_name)?;
let room = mem::replace(room, HashMap::new());
Some(room)
}
fn add_client_to_room(
&mut self,
room_name: &str,
id: Option<usize>,
client: Client,
) -> usize {
let mut id = id.unwrap_or_else(|| rand::random::<usize>());
if let Some(room) = self.rooms.get_mut(room_name) {
loop {
if room.contains_key(&id) {
id = rand::random::<usize>();
} else {
break;
}
}
room.insert(id, client);
return id;
}
// Create a new room for the first client
let mut room: Room = HashMap::new();
room.insert(id, client);
self.rooms.insert(room_name.to_owned(), room);
id
}
fn send_chat_message(
&mut self,
room_name: &str,
msg: &str,
_src: usize,
) -> Option<()> {
let mut room = self.take_room(room_name)?;
for (id, client) in room.drain() {
if client.do_send(ChatMessage(msg.to_owned())).is_ok() {
self.add_client_to_room(room_name, Some(id), client);
}
}
Some(())
}
}
impl Actor for WsChatServer {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.subscribe_async::<LeaveRoom>(ctx);
self.subscribe_async::<SendMessage>(ctx);
}
}
impl Handler<JoinRoom> for WsChatServer {
type Result = MessageResult<JoinRoom>;
fn handle(&mut self, msg: JoinRoom, _ctx: &mut Self::Context) -> Self::Result {
let JoinRoom(room_name, client_name, client) = msg;
let id = self.add_client_to_room(&room_name, None, client);
let join_msg = format!(
"{} joined {}",
client_name.unwrap_or("anon".to_string()),
room_name
);
self.send_chat_message(&room_name, &join_msg, id);
MessageResult(id)
}
}
impl Handler<LeaveRoom> for WsChatServer {
type Result = ();
fn handle(&mut self, msg: LeaveRoom, _ctx: &mut Self::Context) {
if let Some(room) = self.rooms.get_mut(&msg.0) {
room.remove(&msg.1);
}
}
}
impl Handler<ListRooms> for WsChatServer {
type Result = MessageResult<ListRooms>;
fn handle(&mut self, _: ListRooms, _ctx: &mut Self::Context) -> Self::Result {
MessageResult(self.rooms.keys().cloned().collect())
}
}
impl Handler<SendMessage> for WsChatServer {
type Result = ();
fn handle(&mut self, msg: SendMessage, _ctx: &mut Self::Context) {
let SendMessage(room_name, id, msg) = msg;
self.send_chat_message(&room_name, &msg, id);
}
}
impl SystemService for WsChatServer {}
impl Supervised for WsChatServer {}