added websockets example to the guide

This commit is contained in:
ibaryshnikov 2019-06-01 16:17:50 +03:00
parent e16bb9cd38
commit cbedf0bba0
6 changed files with 43 additions and 14 deletions

View File

@ -8,10 +8,10 @@ edition = "2018"
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.44"
wasm-bindgen = "0.2.45"
[dependencies.web-sys]
version = "0.3.21"
version = "0.3.22"
features = [
"ErrorEvent",
"MessageEvent",

View File

@ -21,5 +21,3 @@ http
# or use python
python -m SimpleHTTPServer
```
Make sure that you have `WebSockets` server running

View File

@ -7,4 +7,4 @@
</head>
<bodt>
</bodt>
</html>
</html>

View File

@ -14,16 +14,17 @@ extern "C" {
#[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");
// 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
console_log!("message event, received data {:?}", e.data());
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()));
@ -31,7 +32,7 @@ pub fn start_websocket() -> Result<(), JsValue> {
onmessage_callback.forget();
let onerror_callback = Closure::wrap(Box::new(move |e: ErrorEvent| {
console_log!("error event {:?}", e);
console_log!("error event: {:?}", e);
}) as Box<dyn FnMut(ErrorEvent)>);
ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
onerror_callback.forget();
@ -40,8 +41,8 @@ pub fn start_websocket() -> Result<(), JsValue> {
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),
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()));

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