Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Weird expected a string argument error #25

Open
brandonros opened this issue Nov 12, 2023 · 0 comments
Open

Weird expected a string argument error #25

brandonros opened this issue Nov 12, 2023 · 0 comments

Comments

@brandonros
Copy link

#![no_std]

use ewebsock::{WsReceiver, WsSender};
use js_sys::Promise;
use log::Level;
use tokio::sync::OnceCell;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;

pub static mut WS_SENDER: OnceCell<WsSender> = OnceCell::const_new();
pub static mut WS_RECEIVER: OnceCell<WsReceiver> = OnceCell::const_new();

#[wasm_bindgen]
pub fn init_logging() -> Result<(), JsValue> {
    // init logging
    console_log::init_with_level(Level::Debug)
        .map_err(|_| JsValue::from_str("Failed to init logging"))?;
    // return
    Ok(())
}

#[wasm_bindgen]
pub async fn init_websocket() -> Result<JsValue, JsValue> {
    // init websocket
    log::info!("initializing websocket");
    let (sender, receiver) = ewebsock::connect("ws://127.0.0.1:3000")
        .map_err(|_| JsValue::from_str("Failed to call WebSocket API"))?;
    let _ = unsafe { WS_SENDER.set(sender) };
    let _ = unsafe { WS_RECEIVER.set(receiver) };
    // TODO: we actually need to poll for Event::OnOpened but we can't here until we return and call from another function?
    // return
    let promise = Promise::resolve(&true.into());
    let result = JsFuture::from(promise).await?;
    Ok(result)
}

#[wasm_bindgen]
pub async fn read_from_websocket() -> Result<JsValue, JsValue> {
    for _ in 0..100 {
        let result = unsafe { WS_RECEIVER.get().unwrap().try_recv() };
        if result.is_some() {
            let result = result.unwrap();
            log::info!("{:?}", result);
        }
    }
    // return
    let promise = Promise::resolve(&JsValue::NULL);
    let result = JsFuture::from(promise).await?;
    Ok(result)
}
[package]
name = "websocket_client"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
crate-type = ["cdylib"]

[dependencies]
# logging
log = "0.4.20"
console_log = "1.0.0"
# websocket
ewebsock = "0.4.0"
# webassembly
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console"] }
js-sys = "0.3"
wasm-bindgen-futures = "0.4"
# static init
tokio = { version = "1", features = ["sync"] }

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant