websocket.rs (1218B)
1 // Simplified websocket implementation 2 use std::net::TcpStream; 3 use tungstenite::{connect, stream::MaybeTlsStream, Message, WebSocket}; 4 use url::Url; 5 6 pub struct SimplifiedWS { 7 pub url: Url, 8 pub socket: WebSocket<MaybeTlsStream<TcpStream>>, 9 } 10 11 impl SimplifiedWS { 12 pub fn new(url: &str) -> Result<Self, String> { 13 let url = match Url::parse(url) { 14 Ok(url) => url, 15 Err(err) => return Err(format!("Error parsing url: {}", err)), 16 }; 17 18 let (socket, _) = match connect(&url) { 19 Ok((socket, response)) => (socket, response), 20 Err(err) => return Err(format!("Error connecting to websocket: {}", err)), 21 }; 22 23 Ok(Self { url, socket }) 24 } 25 26 pub fn send_message(&mut self, message: &Message) -> Result<(), String> { 27 match self.socket.write_message(message.clone()) { 28 Ok(_) => Ok(()), 29 Err(err) => Err(format!("Error sending message: {}", err)), 30 } 31 } 32 33 pub fn read_message(&mut self) -> Result<Message, String> { 34 match self.socket.read_message() { 35 Ok(message) => Ok(message), 36 Err(err) => Err(format!("Error reading message: {}", err)), 37 } 38 } 39 }