Skip to content
Snippets Groups Projects
polling.rs 1.41 KiB
Newer Older
scratchyone's avatar
scratchyone committed
use console_error_panic_hook;
scratchyone's avatar
scratchyone committed
use log::{info, Level};
scratchyone's avatar
scratchyone committed
use std::cell::RefCell;
use std::panic;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
scratchyone's avatar
scratchyone committed
use wasm_sockets::{self, ConnectionStatus};
scratchyone's avatar
scratchyone committed

fn main() -> Result<(), JsValue> {
    panic::set_hook(Box::new(console_error_panic_hook::hook));
scratchyone's avatar
scratchyone committed
    // console_log and log macros are used instead of println!
    // so that messages can be seen in the browser console
scratchyone's avatar
scratchyone committed
    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
scratchyone's avatar
scratchyone committed
    // This isn't required when being used within a game engine
    let client = Rc::new(RefCell::new(wasm_sockets::PollingClient::new(
scratchyone's avatar
scratchyone committed
        "wss://echo.websocket.org",
    )?));

    let f = Closure::wrap(Box::new(move || {
scratchyone's avatar
scratchyone committed
        if client.borrow().status() == ConnectionStatus::Connected {
            info!("Sending message");
            client.borrow().send_string("Hello, World!").unwrap();
        }
        // receive() gives you all new websocket messages since receive() was last called
        info!("New messages: {:#?}", client.borrow_mut().receive());
scratchyone's avatar
scratchyone committed
    }) as Box<dyn FnMut()>);
scratchyone's avatar
scratchyone committed

    // Start non-blocking game loop
    setInterval(&f, 100);
scratchyone's avatar
scratchyone committed
    f.forget();

    Ok(())
}
scratchyone's avatar
scratchyone committed
// Bind setInterval to make a basic game loop
scratchyone's avatar
scratchyone committed
#[wasm_bindgen]
extern "C" {
    fn setInterval(closure: &Closure<dyn FnMut()>, time: u32) -> i32;
}