Skip to content
Snippets Groups Projects
Unverified Commit 92d1cc78 authored by scratchyone's avatar scratchyone
Browse files

Finish BlockingClient

parent 90a3f1a9
No related branches found
No related tags found
No related merge requests found
/target /target
Cargo.lock Cargo.lock
.vscode
\ No newline at end of file
...@@ -26,3 +26,10 @@ features = [ ...@@ -26,3 +26,10 @@ features = [
[dev-dependencies] [dev-dependencies]
console_log = "0.2.0" console_log = "0.2.0"
console_error_panic_hook = "0.1.6" console_error_panic_hook = "0.1.6"
wasm-bindgen-futures = "0.4.19"
[dev-dependencies.web-sys]
version = "0.3.22"
features = [
"Window",
]
\ No newline at end of file
use console_error_panic_hook;
use log::{debug, error, info, trace, warn, Level};
use std::cell::RefCell;
use std::panic;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures;
use wasm_sockets::{self, ConnectionStatus};
fn main() -> Result<(), JsValue> {
panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init_with_level(Level::Trace).expect("Failed to enable logging");
info!("Creating connection");
// Client is wrapped in an Rc<RefCell<>> so it can be used within setInterval
let client = Rc::new(RefCell::new(wasm_sockets::BlockingClient::new(
"wss://echo.websocket.org",
)?));
let f = Closure::wrap(Box::new(move || {
info!("{:#?}", client.borrow_mut().receive());
}) as Box<dyn FnMut()>);
setInterval(&f, 100); // Create non-blocking loop
f.forget();
Ok(())
}
#[wasm_bindgen]
extern "C" {
fn setInterval(closure: &Closure<dyn FnMut()>, time: u32) -> i32;
}
File moved
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
</style> </style>
</head> </head>
<script type="module"> <script type="module">
import init from '../target/basic.js'; import init from '../target/blocking.js';
init(); init();
</script> </script>
</html> </html>
...@@ -78,26 +78,26 @@ pub fn start_websocket() -> Result<(), JsValue> { ...@@ -78,26 +78,26 @@ pub fn start_websocket() -> Result<(), JsValue> {
Ok(()) Ok(())
} }
#[derive(Debug)] #[derive(Debug, Clone, PartialEq)]
pub enum ConnectionStatus { pub enum ConnectionStatus {
Connecting, Connecting,
Connected, Connected,
Error(ErrorEvent), Error(ErrorEvent),
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub enum Message { pub enum Message {
Text(String), Text(String),
Binary(Vec<u8>), Binary(Vec<u8>),
} }
pub struct BlockingClient { pub struct BlockingClient {
pub url: String, pub url: String,
pub connection: Rc<RefCell<web_sys::WebSocket>>, pub event_client: EventClient,
pub status: Rc<RefCell<ConnectionStatus>>, pub status: Rc<RefCell<ConnectionStatus>>,
pub data: Rc<RefCell<Vec<String>>>, pub data: Rc<RefCell<Vec<Message>>>,
} }
// TODO: Replace unwraps and JsValue with custom error type // TODO: Replace unwraps and JsValue with custom error type
impl BlockingClient { impl BlockingClient {
pub fn connect_with_url(url: &str) -> Result<Self, JsValue> { pub fn new(url: &str) -> Result<Self, JsValue> {
// Create connection // Create connection
let mut client = EventClient::new(url)?; let mut client = EventClient::new(url)?;
let data = Rc::new(RefCell::new(vec![])); let data = Rc::new(RefCell::new(vec![]));
...@@ -115,13 +115,33 @@ impl BlockingClient { ...@@ -115,13 +115,33 @@ impl BlockingClient {
*status_ref.borrow_mut() = ConnectionStatus::Error(e); *status_ref.borrow_mut() = ConnectionStatus::Error(e);
}))); })));
client.set_on_message(Some(Box::new(move |c: &EventClient, m: Message| {
data_ref.borrow_mut().push(m);
})));
Ok(Self { Ok(Self {
url: url.to_string(), url: url.to_string(),
connection: client.connection, event_client: client,
status, status,
data, data,
}) })
} }
pub fn receive(&mut self) -> Vec<Message> {
let data = (*self.data.borrow()).clone();
(*self.data.borrow_mut()).clear();
data
}
pub fn status(&self) -> ConnectionStatus {
self.status.borrow().clone()
}
pub fn send_string(&self, message: &str) -> Result<(), JsValue> {
self.event_client.send_string(message)
}
pub fn send_binary(&self, message: Vec<u8>) -> Result<(), JsValue> {
self.event_client.send_binary(message)
}
} }
pub struct EventClient { pub struct EventClient {
pub url: Rc<RefCell<String>>, pub url: Rc<RefCell<String>>,
...@@ -257,12 +277,12 @@ impl EventClient { ...@@ -257,12 +277,12 @@ impl EventClient {
} }
pub fn send_string(&self, message: &str) -> Result<(), JsValue> { pub fn send_string(&self, message: &str) -> Result<(), JsValue> {
self.connection.borrow_mut().send_with_str(message) self.connection.borrow().send_with_str(message)
} }
pub fn send_binary(&self, message: Vec<u8>) -> Result<(), JsValue> { pub fn send_binary(&self, message: Vec<u8>) -> Result<(), JsValue> {
self.connection self.connection
.borrow_mut() .borrow()
.send_with_u8_array(message.as_slice()) .send_with_u8_array(message.as_slice())
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment