| 1 |
# WebSockets Example |
| 2 |
|
| 3 |
[View full source code][code] or [view the compiled example online][online] |
| 4 |
|
| 5 |
[online]: https://rustwasm.github.io/wasm-bindgen/exbuild/websockets/ |
| 6 |
[code]: https://github.com/rustwasm/wasm-bindgen/tree/master/examples/websockets/ |
| 7 |
|
| 8 |
This example connects to an echo server on `wss://echo.websocket.org`, |
| 9 |
sends a `ping` message, and receives the response. |
| 10 |
|
| 11 |
## `Cargo.toml` |
| 12 |
|
| 13 |
The `Cargo.toml` enables features necessary to create a `WebSocket` object and |
| 14 |
to access events such as `MessageEvent` or `ErrorEvent`. |
| 15 |
|
| 16 |
```toml |
| 17 |
{{#include ../../../examples/websockets/Cargo.toml}} |
| 18 |
``` |
| 19 |
|
| 20 |
## `src/lib.rs` |
| 21 |
|
| 22 |
This code shows the basic steps required to work with a `WebSocket`. |
| 23 |
At first it opens the connection, then subscribes to events `onmessage`, `onerror`, `onopen`. |
| 24 |
After the socket is opened it sends a `ping` message, receives an echoed response |
| 25 |
and prints it to the browser console. |
| 26 |
|
| 27 |
```rust |
| 28 |
{{#include ../../../examples/websockets/src/lib.rs}} |
| 29 |
``` |