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 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
}

View file

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