Skip to content

Commit

Permalink
impl Drop for server examples (#376)
Browse files Browse the repository at this point in the history
In #373 I raised my confusion about the lack of a disconnection
mechanism in the source code and the examples, but it was pointed out
that `Drop` is the intended way of cleaning up resources.

This PR adds a Drop implementation for three of the server examples, so
that users that refer to these won't be confused about how to implement
their own cleanup.
  • Loading branch information
EpicEric authored Nov 14, 2024
1 parent ad2403b commit bd6dc3a
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
17 changes: 14 additions & 3 deletions russh/examples/echoserver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ async fn main() {

#[derive(Clone)]
struct Server {
clients: Arc<Mutex<HashMap<(usize, ChannelId), russh::server::Handle>>>,
clients: Arc<Mutex<HashMap<usize, (ChannelId, russh::server::Handle)>>>,
id: usize,
}

impl Server {
async fn post(&mut self, data: CryptoVec) {
let mut clients = self.clients.lock().await;
for ((id, channel), ref mut s) in clients.iter_mut() {
for (id, (channel, ref mut s)) in clients.iter_mut() {
if *id != self.id {
let _ = s.data(*channel, data.clone()).await;
}
Expand Down Expand Up @@ -76,7 +76,7 @@ impl server::Handler for Server {
) -> Result<bool, Self::Error> {
{
let mut clients = self.clients.lock().await;
clients.insert((self.id, channel.id()), session.handle());
clients.insert(self.id, (channel.id(), session.handle()));
}
Ok(true)
}
Expand Down Expand Up @@ -135,3 +135,14 @@ impl server::Handler for Server {
Ok(true)
}
}

impl Drop for Server {
fn drop(&mut self) {
let id = self.id;
let clients = self.clients.clone();
tokio::spawn(async move {
let mut clients = clients.lock().await;
clients.remove(&id);
});
}
}
11 changes: 11 additions & 0 deletions russh/examples/ratatui_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,17 @@ impl Handler for AppServer {
}
}

impl Drop for AppServer {
fn drop(&mut self) {
let id = self.id;
let clients = self.clients.clone();
tokio::spawn(async move {
let mut clients = clients.lock().await;
clients.remove(&id);
});
}
}

#[tokio::main]
async fn main() {
let mut server = AppServer::new();
Expand Down
11 changes: 11 additions & 0 deletions russh/examples/ratatui_shared_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,17 @@ impl Handler for AppServer {
}
}

impl Drop for AppServer {
fn drop(&mut self) {
let id = self.id;
let clients = self.clients.clone();
tokio::spawn(async move {
let mut clients = clients.lock().await;
clients.remove(&id);
});
}
}

#[tokio::main]
async fn main() {
let mut server = AppServer::new();
Expand Down

0 comments on commit bd6dc3a

Please sign in to comment.