1 unstable release
new 0.1.0 | Nov 22, 2024 |
---|
#108 in WebSocket
6KB
typed-websocket
simple wrapper on top of websocket stream that enforces type
use case
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tokio_tungstenite::connect_async;
use url::Url;
let url = Url::parse("wss://example.com/socket")?;
let (stream, _) = connect_async(url).await?;
// Create a TypedWebSocketStream with specific input/output types
let mut ws: TypedWebSocketStream<_, RequestMessage, ResponseMessage> = TypedWebSocketStream::new(stream);
// Send a message
let outgoing = RequestMessage::new();
ws.send(outgoing).await?;
// Receive a message
match ws.receive().await {
Ok(incoming) => println!("Received: {:?}", incoming),
Err(e) => eprintln!("Error receiving message: {}", e),
}
// Close the connection
ws.close().await?;
Ok(())
}
requirement
- INPUT: impl Serialize
- OUTPUT: impl Deserialize
// Define input and output message types
#[derive(Serialize, Debug)]
struct RequestMessage {
command: String,
data: String,
}
#[derive(Deserialize, Debug)]
struct ResponseMessage {
response: String,
status: u16,
}
notes
Dependencies
~4–11MB
~112K SLoC