tokio_tungstenite_wasm/
lib.rs1mod error;
2mod message;
3#[cfg(not(target_arch = "wasm32"))]
4mod native;
5#[cfg(target_arch = "wasm32")]
6mod web;
7
8pub use error::{Error, Result};
9pub use message::coding::*;
10pub use message::CloseFrame;
11pub use message::Message;
12#[cfg(not(target_arch = "wasm32"))]
13use native as ws;
14#[cfg(target_arch = "wasm32")]
15use web as ws;
16pub use ws::{Bytes, Utf8Bytes, WebSocketStream};
17
18pub async fn connect<S: AsRef<str>>(url: S) -> Result<WebSocketStream> {
19 ws::connect(url.as_ref()).await
20}
21
22pub async fn connect_with_protocols<S: AsRef<str>>(
23 url: S,
24 protocols: &[&str],
25) -> Result<WebSocketStream> {
26 ws::connect_with_protocols(url.as_ref(), protocols).await
27}
28
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn assert_impls() {
35 use assert_impl::assert_impl;
36
37 assert_impl!(futures_util::Stream<Item = Result<Message>>: WebSocketStream);
38 assert_impl!(futures_util::Sink<Message>: WebSocketStream);
39 }
40}
41
42#[cfg(all(test, not(target_arch = "wasm32")))]
43mod native_tests {
44 use super::*;
45 use futures_util::{SinkExt, StreamExt};
46
47 #[tokio::test]
48 async fn ping_test() {
49 let port = rand::random();
50 let ip_addr = std::net::Ipv4Addr::from([127, 0, 0, 1]);
51 let listener = tokio::net::TcpListener::bind((ip_addr, port))
52 .await
53 .unwrap();
54
55 let payload = vec![0, 1, 2];
56 let pong = tokio_tungstenite::tungstenite::Message::Pong(payload.clone().into());
57 let handle: tokio::task::JoinHandle<crate::Result<_>> = tokio::spawn(async move {
58 let (stream, _) = listener.accept().await?;
59 let ping = tokio_tungstenite::tungstenite::Message::Ping(payload.into());
60
61 let ws = tokio_tungstenite::accept_async(stream).await.unwrap();
62 let (mut write, mut read) = ws.split();
63 write.send(ping).await?;
64 let timeout = std::time::Duration::from_millis(500);
65 tokio::time::timeout(timeout, read.next())
66 .await
67 .map_err(|_| crate::Error::AlreadyClosed)
68 });
69
70 let mut client = connect(format!("ws://127.0.0.1:{}", port)).await.unwrap();
71 assert!(client.next().await.is_some());
72 assert!(client.next().await.is_none());
73 let result = handle.await.unwrap().unwrap().unwrap().unwrap();
74 assert_eq!(result, pong);
75 }
76}