Merge pull request #1546 from ibaryshnikov/websockets-example

added websockets example
This commit is contained in:
Alex Crichton 2019-06-03 09:33:39 -05:00 committed by GitHub
commit 9884c79bd9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 141 additions and 1 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

@ -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;

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.45"
[dependencies.web-sys]
version = "0.3.22"
features = [
"ErrorEvent",
"MessageEvent",
"WebSocket",
]

View File

@ -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
```

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,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(())
}

View File

@ -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)

View File

@ -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}}
```