11 releases (6 breaking)

✓ Uses Rust 2018 edition

new 0.6.0 Mar 21, 2020
0.5.1 Nov 14, 2019
0.1.0 Jul 19, 2019

#7 in WebSocket

Download history 28/week @ 2019-12-02 27/week @ 2019-12-09 2/week @ 2019-12-16 9/week @ 2019-12-23 1/week @ 2019-12-30 15/week @ 2020-01-06 14/week @ 2020-01-13 56/week @ 2020-01-20 20/week @ 2020-01-27 2/week @ 2020-02-03 41/week @ 2020-02-10 29/week @ 2020-02-17 48/week @ 2020-02-24 1/week @ 2020-03-02 44/week @ 2020-03-09 37/week @ 2020-03-16

98 downloads per month

Unlicense

51KB
777 lines

ws_stream_wasm

standard-readme compliant Build Status Docs crates.io

A convenience library for using web sockets in WASM

features:

  • [WsMeta]: A wrapper around [web_sys::WebSocket].
  • [WsMessage]: A simple rusty representation of a WebSocket message.
  • [WsStream]: A futures Sink/Stream of WsMessage. It also has a method into_io() which let's you get a wrapper that implements AsyncRead/AsyncWrite (tokio version behind the feature tokio_io).
  • [WsEvent]: [WsMeta] is observable with pharos for events (mainly useful for connection close).

NOTE: this crate only works on WASM. If you want a server side equivalent that implements AsyncRead/AsyncWrite over WebSockets, check out ws_stream_tungstenite.

missing features:

  • no automatic reconnect
  • not all features are thoroughly tested. Notably, I have little use for extensions and sub-protocols. Tungstenite, which I use for the server end (and for automated testing) doesn't support these, making it hard to write unit tests.

Table of Contents

Install

With cargo add: cargo add ws_stream_wasm

With cargo yaml:

dependencies:

  ws_stream_wasm: ^0.6

With raw Cargo.toml

[dependencies]

   ws_stream_wasm = "0.6"

Upgrade

Please check out the changelog when upgrading.

Dependencies

This crate has few dependencies. Cargo will automatically handle it's dependencies for you.

There is one optional features. The tokio_io features causes the WsIo returned from [WsStream::into_io] to implement the tokio version of AsyncRead/AsyncWrite.

Usage

The integration tests show most features in action. The example directory doesn't currently hold any interesting examples.

The types in this library are Send as far as the compiler is concerned. This is so that you can use them with general purpose libraries that also work on WASM but that require a connection to be Send. Currently WASM has no threads though and most underlying types we use aren't Send. The solution for the moment is to use [send_wrapper::SendWrapper]. This will panic if it's ever dereferenced on a different thread than where it's created. You have to consider that the types aren't Send, but on WASM it's safe to pass them to an API that requires Send, because there is no multi-threading.

The main entrypoint you'll want to use, eg to connect, is [WsMeta::connect].

Basic events example

use
{
   ws_stream_wasm       :: *                        ,
   pharos               :: *                        ,
   wasm_bindgen         :: UnwrapThrowExt           ,
   wasm_bindgen_futures :: futures_0_3::spawn_local ,
   futures              :: stream::StreamExt        ,
};

let program = async
{
   let (mut ws, _wsio) = WsMeta::connect( "127.0.0.1:3012", None ).await

      .expect_throw( "assume the connection succeeds" );

   let mut evts = ws.observe( ObserveConfig::default() ).expect_throw( "observe" );

   ws.close().await;

   // Note that since WsMeta::connect resolves to an opened connection, we don't see
   // any Open events here.
   //
   assert!( evts.next().await.unwrap_throw().is_closing() );
   assert!( evts.next().await.unwrap_throw().is_closed () );
};

spawn_local( program );

Filter events example

This shows how to filter events. The functionality comes from pharos which we use to make [WsMeta] observable.

use
{
   ws_stream_wasm       :: *                        ,
   pharos               :: *                        ,
   wasm_bindgen         :: UnwrapThrowExt           ,
   wasm_bindgen_futures :: futures_0_3::spawn_local ,
   futures              :: stream::StreamExt        ,
};

let program = async
{
   let (mut ws, _wsio) = WsMeta::connect( "127.0.0.1:3012", None ).await

      .expect_throw( "assume the connection succeeds" );

   // The Filter type comes from the pharos crate.
   //
   let mut evts = ws.observe( Filter::Pointer( WsEvent::is_closed ).into() ).expect_throw( "observe" );

   ws.close().await;

   // Note we will only get the closed event here, the WsEvent::Closing has been filtered out.
   //
   assert!( evts.next().await.unwrap_throw().is_closed () );
};

spawn_local( program );

API

Api documentation can be found on docs.rs.

References

The reference documents for understanding web sockets and how the browser handles them are:

Contributing

Please check out the contribution guidelines.

Testing

For testing we need back-end servers to echo data back to the tests. These are in the ws_stream_tungstenite crate.

git clone https://github.com/najamelan/ws_stream_tungstenite
cd ws_stream_tungstenite
cargo run --example echo --release

# in a different terminal:
cargo run --example echo_tt --release -- "127.0.0.1:3312"

# the second server is pure async-tungstenite without ws_stream_tungstenite wrapping it in AsyncRead/Write. This
# is needed for testing a WsMessage::Text because ws_stream_tungstenite only does binary.

# in a third terminal, in ws_stream_wasm you have different options:
wasm-pack test --firefox [--headless] [--release]
wasm-pack test --chrome  [--headless] [--release]

In general chrome is well faster. When running it in the browser (without --headless) you get trace logging in the console, which helps debugging. In chrome you need to enable verbose output in the console, otherwise only info and up level are reported.

Code of conduct

Any of the behaviors described in point 4 "Unacceptable Behavior" of the Citizens Code of Conduct are not welcome here and might get you banned. If anyone, including maintainers and moderators of the project, fail to respect these/your limits, you are entitled to call them out.

License

Unlicence

Dependencies

~9.5MB
~186K SLoC