Channels as a wrapped type, chat?

This commit is contained in:
Dane Johnson 2022-10-12 17:34:02 -05:00
parent 152e7926ee
commit 6189b82bd3
2 changed files with 41 additions and 5 deletions

View File

@ -1,17 +1,18 @@
use std::sync::Arc;
use tokio::sync::{ mpsc, Mutex};
use tokio::sync::{ mpsc, Mutex };
use tokio::sync::mpsc::error::TryRecvError;
use crate::message::Message;
#[derive(Clone)]
pub struct GameController {
pub channels: Arc<Mutex<Vec<Channel>>>,
pub channels: Arc<Mutex<Channels>>,
}
impl std::default::Default for GameController {
fn default() -> Self {
let channels = Arc::new(Mutex::new(Vec::new()));
let channels = Arc::new(Mutex::new(Channels::default()));
GameController { channels }
}
}
@ -21,6 +22,29 @@ pub struct Channel {
pub rx: mpsc::Receiver<Message>,
}
#[derive(Default)]
pub struct Channels(Vec<Channel>);
impl Channels {
pub fn try_recv(&mut self) -> Result<Message, TryRecvError> {
for channel in self.0.iter_mut() {
let res = channel.rx.try_recv();
if !(res == Err(TryRecvError::Empty)) {
return res
}
}
Err(TryRecvError::Empty)
}
pub async fn broadcast(&mut self, msg: Message) {
for channel in self.0.iter_mut() {
channel.tx.send(msg.clone()).await.unwrap();
}
}
pub fn push(&mut self, channel: Channel) {
self.0.push(channel);
}
}
pub fn channel_pair() -> (Channel, Channel) {
let (atx, brx) = mpsc::channel(32);
let (btx, arx) = mpsc::channel(32);
@ -29,6 +53,18 @@ pub fn channel_pair() -> (Channel, Channel) {
impl GameController {
pub async fn run_loop(&self) {
todo!();
loop {
let mut channels = self.channels.lock().await;
if let Ok(msg) = channels.try_recv() {
dispatch(&mut channels, msg).await;
}
}
}
}
async fn dispatch(channels: &mut Channels, msg: Message) {
match msg.command.as_str() {
"CHAT" => channels.broadcast(msg).await,
_ => ()
};
}

View File

@ -5,7 +5,7 @@ use lazy_static::lazy_static;
use tokio::net::TcpStream;
use tokio_tungstenite::{tungstenite::Message as WsMessage, WebSocketStream};
#[derive(PartialEq, Debug)]
#[derive(PartialEq, Debug, Clone)]
pub struct Message {
pub command: String,
pub args: Vec<String>,