From 366aec054f874fe5e382e7e295de13eae7cae40a Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sat, 12 Oct 2024 19:33:49 +0200 Subject: [PATCH] close connection on drop --- crates/servicepoint/Cargo.toml | 4 ++++ crates/servicepoint/examples/websocket.rs | 27 +++++++++++++++++++++++ crates/servicepoint/src/connection.rs | 10 ++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 crates/servicepoint/examples/websocket.rs diff --git a/crates/servicepoint/Cargo.toml b/crates/servicepoint/Cargo.toml index f66a607..20ae963 100644 --- a/crates/servicepoint/Cargo.toml +++ b/crates/servicepoint/Cargo.toml @@ -43,6 +43,10 @@ required-features = ["rand"] name = "game_of_life" required-features = ["rand"] +[[example]] +name = "websocket" +required-features = ["protocol_websocket"] + [dev-dependencies] # for examples clap = { version = "4.5", features = ["derive"] } diff --git a/crates/servicepoint/examples/websocket.rs b/crates/servicepoint/examples/websocket.rs new file mode 100644 index 0000000..71be6a3 --- /dev/null +++ b/crates/servicepoint/examples/websocket.rs @@ -0,0 +1,27 @@ +//! Example for how to use the WebSocket connection + +use servicepoint::{ + Command, CompressionCode, Connection, Grid, Origin, PixelGrid, +}; + +fn main() { + // make connection mut + let mut connection = + Connection::open_websocket("ws://localhost:8080".parse().unwrap()) + .unwrap(); + + // use send_mut instead of send + connection.send_mut(Command::Clear).unwrap(); + + let mut pixels = PixelGrid::max_sized(); + pixels.fill(true); + + // use send_mut instead of send + connection + .send_mut(Command::BitmapLinearWin( + Origin::ZERO, + pixels, + CompressionCode::Lzma, + )) + .unwrap(); +} diff --git a/crates/servicepoint/src/connection.rs b/crates/servicepoint/src/connection.rs index dd2706a..c12f341 100644 --- a/crates/servicepoint/src/connection.rs +++ b/crates/servicepoint/src/connection.rs @@ -111,7 +111,6 @@ impl Connection { let request = ClientRequestBuilder::new(uri).into_client_request()?; let (sock, _) = connect(request)?; - Ok(Self::WebSocket(sock)) } @@ -208,6 +207,15 @@ impl Connection { } } +impl Drop for Connection { + fn drop(&mut self) { + #[cfg(feature = "protocol_websocket")] + if let Connection::WebSocket(sock) = self { + _ = sock.close(None); + } + } +} + #[cfg(test)] mod tests { use super::*;