added websockets example

This commit is contained in:
ibaryshnikov
2019-05-20 02:01:25 +03:00
parent ad68436cc9
commit 6825da384f
6 changed files with 111 additions and 0 deletions

View File

@ -78,6 +78,7 @@ members = [
"examples/wasm2js",
"examples/webaudio",
"examples/webgl",
"examples/websockets",
"examples/without-a-bundler",
"examples/without-a-bundler-no-modules",
"tests/no-std",

View File

@ -0,0 +1,19 @@
[package]
name = "websockets"
version = "0.1.0"
authors = ["The wasm-bindgen Developers"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.44"
[dependencies.web-sys]
version = "0.3.21"
features = [
"ErrorEvent",
"MessageEvent",
"WebSocket",
]

View File

@ -0,0 +1,25 @@
# WebSockets Example
[View documentation for this example online][dox] or [View compiled example
online][compiled]
[compiled]: https://rustwasm.github.io/wasm-bindgen/exbuild/websockets/
[dox]: https://rustwasm.github.io/wasm-bindgen/examples/websockets.html
You can build the example locally with:
```
$ wasm-pack build --target web
```
Then serve the statics and navigate to `host:port`
```
# static server from https://crates.io/crates/https
http
# or use python
python -m SimpleHTTPServer
```
Make sure that you have `WebSockets` server running

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSockets example</title>
<script type="module" src="index.js"></script>
</head>
<bodt>
</bodt>
</html>

View File

@ -0,0 +1,5 @@
import init from './pkg/websockets.js';
window.addEventListener('load', async () => {
await init('./pkg/websockets_bg.wasm');
});

View File

@ -0,0 +1,51 @@
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{ErrorEvent, MessageEvent, WebSocket};
macro_rules! console_log {
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen(start)]
pub fn start_websocket() -> Result<(), JsValue> {
// Assuming, you run a WebSockets server at localhost:8081
// You'll also need to disable CORS in case of serving this example from
// the different `host:port` then your WebSockets server
let ws = WebSocket::new("ws://localhost:8081")
.expect("should create a socket");
// create callback
let onmessage_callback = Closure::wrap(Box::new(move |e: MessageEvent| {
// handle message
console_log!("message event, received data {:?}", e.data());
}) as Box<dyn FnMut(MessageEvent)>);
// set message event handler on WebSocket
ws.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
// forget the callback to keep it alive
onmessage_callback.forget();
let onerror_callback = Closure::wrap(Box::new(move |e: ErrorEvent| {
console_log!("error event {:?}", e);
}) as Box<dyn FnMut(ErrorEvent)>);
ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
onerror_callback.forget();
let cloned_ws = ws.clone();
let onopen_callback = Closure::wrap(Box::new(move |_| {
console_log!("socket opened");
match cloned_ws.send_with_str("ping") {
Ok(_) => console_log!("message sent successfully"),
Err(err) => console_log!("error sending message {:?}", err),
}
}) as Box<dyn FnMut(JsValue)>);
ws.set_onopen(Some(onopen_callback.as_ref().unchecked_ref()));
onopen_callback.forget();
Ok(())
}