From b6c3c69777781df68c69febf48f863aff1a5b400 Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Sat, 13 Feb 2021 21:46:35 -0500 Subject: [PATCH] Create struct for client agent --- src/main.rs | 4 +-- src/net/agent.rs | 77 +++++++++++++++++++++++++++++------------------- 2 files changed, 48 insertions(+), 33 deletions(-) diff --git a/src/main.rs b/src/main.rs index 48ae34b..341dbdd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,7 @@ use ws::{Message, WebSocket}; use path::Tail; use net::{ - agent::run_client, + agent::ClientAgent, server::{Handle, Server}, ClientMessage, ServerMessage, }; @@ -114,5 +114,5 @@ async fn handle_socket(game_server: Handle, websocket: WebSocket) -> Result<()> }) }); - run_client(game_server, &mut websocket).await + ClientAgent::new(game_server).run(&mut websocket).await } diff --git a/src/net/agent.rs b/src/net/agent.rs index ee261d3..519b2c5 100644 --- a/src/net/agent.rs +++ b/src/net/agent.rs @@ -4,40 +4,55 @@ use futures::{channel::mpsc::*, prelude::*, Stream}; use super::server::Handle; use super::*; -pub async fn run_client( - handle: Handle, - socket: &mut (impl Stream> - + Sink - + Send - + Unpin), -) -> Result<()> { - let (sender, mut receiver) = channel(CHANNEL_BUFFER); +pub struct ClientAgent { + server: Handle, +} - // register player - let player_id = handle.lock().await.add_player(sender, &handle).await?; +impl ClientAgent { + pub fn new(server: Handle) -> ClientAgent { + ClientAgent { server } + } - // main message loop - let result: Result<()> = async { - loop { - tokio::select! { - client_message = socket.next() => { - match client_message { - Some(msg) => - handle.lock().await.process_message(player_id, msg?), - None => break Ok(()), - } - }, - Some(server_message) = receiver.next() => { - socket.send(server_message).await? - }, - else => break Ok(()), + pub async fn run( + &mut self, + socket: &mut (impl Stream> + + Sink + + Send + + Unpin), + ) -> Result<()> { + let (sender, mut receiver) = channel(CHANNEL_BUFFER); + + // register player + let player_id = self + .server + .lock() + .await + .add_player(sender, &self.server) + .await?; + + // main message loop + let result: Result<()> = async { + loop { + tokio::select! { + client_message = socket.next() => { + match client_message { + Some(msg) => + self.server.lock().await.process_message(player_id, msg?), + None => break Ok(()), + } + }, + Some(server_message) = receiver.next() => { + socket.send(server_message).await? + }, + else => break Ok(()), + } } } + .await; + + // deregister player, whether normally or due to error + self.server.lock().await.remove_player(player_id); + + result } - .await; - - // deregister player, whether normally or due to error - handle.lock().await.remove_player(player_id); - - result }