Skip to content

added websockets example #1546

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

Merged
merged 3 commits into from
Jun 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ jobs:
- script: mv _package.json package.json && npm install && rm package.json
displayName: "run npm install"
- script: |
for dir in `ls examples | grep -v README | grep -v asm.js | grep -v raytrace | grep -v without-a-bundler`; do
for dir in `ls examples | grep -v README | grep -v asm.js | grep -v raytrace | grep -v without-a-bundler | grep -v websockets`; do
(cd examples/$dir &&
ln -fs ../../node_modules . &&
npm run build -- --output-path $BUILD_ARTIFACTSTAGINGDIRECTORY/exbuild/$dir) || exit 1;
Expand Down
19 changes: 19 additions & 0 deletions examples/websockets/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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.45"

[dependencies.web-sys]
version = "0.3.22"
features = [
"ErrorEvent",
"MessageEvent",
"WebSocket",
]
23 changes: 23 additions & 0 deletions examples/websockets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 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
```
10 changes: 10 additions & 0 deletions examples/websockets/index.html
Original file line number Diff line number Diff line change
@@ -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>
5 changes: 5 additions & 0 deletions examples/websockets/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import init from './pkg/websockets.js';

window.addEventListener('load', async () => {
await init('./pkg/websockets_bg.wasm');
});
52 changes: 52 additions & 0 deletions examples/websockets/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
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> {
// Connect to an echo server
let ws = WebSocket::new("wss://echo.websocket.org")?;

// create callback
let onmessage_callback = Closure::wrap(Box::new(move |e: MessageEvent| {
// handle message
let response = e
.data()
.as_string()
.expect("Can't convert received data to a string");
console_log!("message event, received data: {:?}", response);
}) 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 successfully sent"),
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(())
}
1 change: 1 addition & 0 deletions guide/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- [web-sys: `canvas` Julia set](./examples/julia.md)
- [web-sys: WebAudio](./examples/web-audio.md)
- [web-sys: WebGL](./examples/webgl.md)
- [web-sys: WebSockets](./examples/websockets.md)
- [web-sys: `requestAnimationFrame`](./examples/request-animation-frame.md)
- [web-sys: A Simple Paint Program](./examples/paint.md)
- [Parallel Raytracing](./examples/raytrace.md)
Expand Down
29 changes: 29 additions & 0 deletions guide/src/examples/websockets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# WebSockets Example

[View full source code][code] or [view the compiled example online][online]

[online]: https://rustwasm.github.io/wasm-bindgen/exbuild/websockets/
[code]: https://github.com/rustwasm/wasm-bindgen/tree/master/examples/websockets/

This example connects to an echo server on `wss://echo.websocket.org`,
sends a `ping` message, and receives the response.

## `Cargo.toml`

The `Cargo.toml` enables features necessary to create a `WebSocket` object and
to access events such as `MessageEvent` or `ErrorEvent`.

```toml
{{#include ../../../examples/websockets/Cargo.toml}}
```

## `src/lib.rs`

This code shows the basic steps required to work with a `WebSocket`.
At first it opens the connection, then subscribes to events `onmessage`, `onerror`, `onopen`.
After the socket is opened it sends a `ping` message, receives an echoed response
and prints it to the browser console.

```rust
{{#include ../../../examples/websockets/src/lib.rs}}
```