Skip to content

Commit 6825da3

Browse files
committed
added websockets example
1 parent ad68436 commit 6825da3

File tree

6 files changed

+111
-0
lines changed

6 files changed

+111
-0
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ members = [
7878
"examples/wasm2js",
7979
"examples/webaudio",
8080
"examples/webgl",
81+
"examples/websockets",
8182
"examples/without-a-bundler",
8283
"examples/without-a-bundler-no-modules",
8384
"tests/no-std",

examples/websockets/Cargo.toml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
[package]
2+
name = "websockets"
3+
version = "0.1.0"
4+
authors = ["The wasm-bindgen Developers"]
5+
edition = "2018"
6+
7+
[lib]
8+
crate-type = ["cdylib"]
9+
10+
[dependencies]
11+
wasm-bindgen = "0.2.44"
12+
13+
[dependencies.web-sys]
14+
version = "0.3.21"
15+
features = [
16+
"ErrorEvent",
17+
"MessageEvent",
18+
"WebSocket",
19+
]

examples/websockets/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# WebSockets Example
2+
3+
[View documentation for this example online][dox] or [View compiled example
4+
online][compiled]
5+
6+
[compiled]: https://rustwasm.github.io/wasm-bindgen/exbuild/websockets/
7+
[dox]: https://rustwasm.github.io/wasm-bindgen/examples/websockets.html
8+
9+
You can build the example locally with:
10+
11+
```
12+
$ wasm-pack build --target web
13+
```
14+
15+
Then serve the statics and navigate to `host:port`
16+
17+
```
18+
# static server from https://crates.io/crates/https
19+
http
20+
21+
# or use python
22+
python -m SimpleHTTPServer
23+
```
24+
25+
Make sure that you have `WebSockets` server running

examples/websockets/index.html

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8">
5+
<title>WebSockets example</title>
6+
<script type="module" src="index.js"></script>
7+
</head>
8+
<bodt>
9+
</bodt>
10+
</html>

examples/websockets/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import init from './pkg/websockets.js';
2+
3+
window.addEventListener('load', async () => {
4+
await init('./pkg/websockets_bg.wasm');
5+
});

examples/websockets/src/lib.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use wasm_bindgen::prelude::*;
2+
use wasm_bindgen::JsCast;
3+
use web_sys::{ErrorEvent, MessageEvent, WebSocket};
4+
5+
macro_rules! console_log {
6+
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
7+
}
8+
9+
#[wasm_bindgen]
10+
extern "C" {
11+
#[wasm_bindgen(js_namespace = console)]
12+
fn log(s: &str);
13+
}
14+
15+
#[wasm_bindgen(start)]
16+
pub fn start_websocket() -> Result<(), JsValue> {
17+
// Assuming, you run a WebSockets server at localhost:8081
18+
// You'll also need to disable CORS in case of serving this example from
19+
// the different `host:port` then your WebSockets server
20+
let ws = WebSocket::new("ws://localhost:8081")
21+
.expect("should create a socket");
22+
23+
// create callback
24+
let onmessage_callback = Closure::wrap(Box::new(move |e: MessageEvent| {
25+
// handle message
26+
console_log!("message event, received data {:?}", e.data());
27+
}) as Box<dyn FnMut(MessageEvent)>);
28+
// set message event handler on WebSocket
29+
ws.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
30+
// forget the callback to keep it alive
31+
onmessage_callback.forget();
32+
33+
let onerror_callback = Closure::wrap(Box::new(move |e: ErrorEvent| {
34+
console_log!("error event {:?}", e);
35+
}) as Box<dyn FnMut(ErrorEvent)>);
36+
ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
37+
onerror_callback.forget();
38+
39+
let cloned_ws = ws.clone();
40+
let onopen_callback = Closure::wrap(Box::new(move |_| {
41+
console_log!("socket opened");
42+
match cloned_ws.send_with_str("ping") {
43+
Ok(_) => console_log!("message sent successfully"),
44+
Err(err) => console_log!("error sending message {:?}", err),
45+
}
46+
}) as Box<dyn FnMut(JsValue)>);
47+
ws.set_onopen(Some(onopen_callback.as_ref().unchecked_ref()));
48+
onopen_callback.forget();
49+
50+
Ok(())
51+
}

0 commit comments

Comments
 (0)