close connection on drop

This commit is contained in:
Vinzenz Schroeter 2024-10-12 19:33:49 +02:00
parent 5f8f691464
commit 366aec054f
3 changed files with 40 additions and 1 deletions

View file

@ -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"] }

View file

@ -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();
}

View file

@ -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::*;