Create struct for client agent

This commit is contained in:
Tangent Wantwight 2021-02-13 21:46:35 -05:00
parent 3f6b55dcc4
commit b6c3c69777
2 changed files with 48 additions and 33 deletions

View file

@ -16,7 +16,7 @@ use ws::{Message, WebSocket};
use path::Tail; use path::Tail;
use net::{ use net::{
agent::run_client, agent::ClientAgent,
server::{Handle, Server}, server::{Handle, Server},
ClientMessage, ServerMessage, 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
} }

View file

@ -4,8 +4,17 @@ use futures::{channel::mpsc::*, prelude::*, Stream};
use super::server::Handle; use super::server::Handle;
use super::*; use super::*;
pub async fn run_client( pub struct ClientAgent {
handle: Handle, server: Handle,
}
impl ClientAgent {
pub fn new(server: Handle) -> ClientAgent {
ClientAgent { server }
}
pub async fn run(
&mut self,
socket: &mut (impl Stream<Item = Result<ClientMessage, Error>> socket: &mut (impl Stream<Item = Result<ClientMessage, Error>>
+ Sink<ServerMessage, Error = Error> + Sink<ServerMessage, Error = Error>
+ Send + Send
@ -14,7 +23,12 @@ pub async fn run_client(
let (sender, mut receiver) = channel(CHANNEL_BUFFER); let (sender, mut receiver) = channel(CHANNEL_BUFFER);
// register player // register player
let player_id = handle.lock().await.add_player(sender, &handle).await?; let player_id = self
.server
.lock()
.await
.add_player(sender, &self.server)
.await?;
// main message loop // main message loop
let result: Result<()> = async { let result: Result<()> = async {
@ -23,7 +37,7 @@ pub async fn run_client(
client_message = socket.next() => { client_message = socket.next() => {
match client_message { match client_message {
Some(msg) => Some(msg) =>
handle.lock().await.process_message(player_id, msg?), self.server.lock().await.process_message(player_id, msg?),
None => break Ok(()), None => break Ok(()),
} }
}, },
@ -37,7 +51,8 @@ pub async fn run_client(
.await; .await;
// deregister player, whether normally or due to error // deregister player, whether normally or due to error
handle.lock().await.remove_player(player_id); self.server.lock().await.remove_player(player_id);
result result
} }
}