use rsurl::aio::{WebSocket, WsMessage, WsSink, WsStream};
use crate::error::{Error, Result};
pub enum Incoming {
Packet(Vec<u8>),
Closed,
}
pub async fn connect(host: &str, path: &str) -> Result<(WsSink, WsStream)> {
let url = format!("wss://{host}{path}");
let ws = WebSocket::connect(&url)
.await
.map_err(|e| Error::Ws(e.to_string()))?;
Ok(ws.split())
}
pub async fn recv_packet(stream: &mut WsStream) -> Result<Incoming> {
loop {
match stream.recv().await {
Some(Ok(WsMessage::Binary(data))) => return Ok(Incoming::Packet(data)),
Some(Ok(WsMessage::Text(_))) => continue, Some(Err(e)) => return Err(Error::Ws(e.to_string())),
None => return Ok(Incoming::Closed),
}
}
}