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,40 +4,55 @@ 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,
socket: &mut (impl Stream<Item = Result<ClientMessage, Error>> }
+ Sink<ServerMessage, Error = Error>
+ Send
+ Unpin),
) -> Result<()> {
let (sender, mut receiver) = channel(CHANNEL_BUFFER);
// register player impl ClientAgent {
let player_id = handle.lock().await.add_player(sender, &handle).await?; pub fn new(server: Handle) -> ClientAgent {
ClientAgent { server }
}
// main message loop pub async fn run(
let result: Result<()> = async { &mut self,
loop { socket: &mut (impl Stream<Item = Result<ClientMessage, Error>>
tokio::select! { + Sink<ServerMessage, Error = Error>
client_message = socket.next() => { + Send
match client_message { + Unpin),
Some(msg) => ) -> Result<()> {
handle.lock().await.process_message(player_id, msg?), let (sender, mut receiver) = channel(CHANNEL_BUFFER);
None => break Ok(()),
} // register player
}, let player_id = self
Some(server_message) = receiver.next() => { .server
socket.send(server_message).await? .lock()
}, .await
else => break Ok(()), .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
} }