Skip to content
Snippets Groups Projects
event.rs 1.23 KiB
Newer Older
scratchyone's avatar
scratchyone committed
use console_error_panic_hook;
scratchyone's avatar
scratchyone committed
use console_log;
use log::{error, info, Level};
scratchyone's avatar
scratchyone committed
use std::panic;
scratchyone's avatar
scratchyone committed
use wasm_bindgen::JsValue;
use wasm_sockets;
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");

scratchyone's avatar
scratchyone committed
    let mut client = wasm_sockets::EventClient::new("wss://echo.websocket.org")?;
scratchyone's avatar
scratchyone committed
    client.set_on_error(Some(Box::new(|error| {
        error!("{:#?}", error);
scratchyone's avatar
scratchyone committed
    })));
scratchyone's avatar
scratchyone committed
    client.set_on_connection(Some(Box::new(|client: &wasm_sockets::EventClient, e| {
        info!("{:#?}", client.status);
scratchyone's avatar
scratchyone committed
        info!("Sending message...");
scratchyone's avatar
scratchyone committed
        client.send_string("Hello, World!").unwrap();
        client.send_binary(vec![20]).unwrap();
scratchyone's avatar
scratchyone committed
    })));
scratchyone's avatar
scratchyone committed
    client.set_on_close(Some(Box::new(|| {
scratchyone's avatar
scratchyone committed
        info!("Connection closed");
scratchyone's avatar
scratchyone committed
    })));
scratchyone's avatar
scratchyone committed
    client.set_on_message(Some(Box::new(
scratchyone's avatar
scratchyone committed
        |client: &wasm_sockets::EventClient, message: wasm_sockets::Message| {
            info!("New Message: {:#?}", message);
scratchyone's avatar
scratchyone committed
        },
    )));

    info!("Connection successfully created");
    Ok(())
}