2020-04-26 17:37:29 +00:00
|
|
|
//! A WebSocket+TLS client based on `async-tungstenite` and `async-native-tls`.
|
|
|
|
//!
|
|
|
|
//! First start a server:
|
|
|
|
//!
|
|
|
|
//! ```
|
|
|
|
//! cargo run --example websocket-server
|
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//! Then start a client:
|
|
|
|
//!
|
|
|
|
//! ```
|
|
|
|
//! cargo run --example websocket-client
|
|
|
|
//! ```
|
|
|
|
|
2020-07-15 09:37:50 +00:00
|
|
|
use std::net::{TcpStream, ToSocketAddrs};
|
2020-03-29 15:59:28 +00:00
|
|
|
use std::pin::Pin;
|
|
|
|
use std::task::{Context, Poll};
|
|
|
|
|
|
|
|
use anyhow::{bail, Context as _, Result};
|
2020-04-06 20:19:54 +00:00
|
|
|
use async_native_tls::{Certificate, TlsConnector, TlsStream};
|
2023-08-06 07:22:57 +00:00
|
|
|
use async_tungstenite::{tungstenite, WebSocketStream};
|
2020-07-19 22:55:35 +00:00
|
|
|
use futures::sink::{Sink, SinkExt};
|
2020-07-23 10:24:16 +00:00
|
|
|
use smol::{prelude::*, Async};
|
2020-03-29 15:59:28 +00:00
|
|
|
use tungstenite::handshake::client::Response;
|
|
|
|
use tungstenite::Message;
|
|
|
|
use url::Url;
|
|
|
|
|
2020-04-26 17:37:29 +00:00
|
|
|
/// Connects to a WebSocket address (optionally secured by TLS).
|
2020-04-06 20:19:54 +00:00
|
|
|
async fn connect(addr: &str, tls: TlsConnector) -> Result<(WsStream, Response)> {
|
2020-03-29 15:59:28 +00:00
|
|
|
// Parse the address.
|
|
|
|
let url = Url::parse(addr)?;
|
|
|
|
let host = url.host_str().context("cannot parse host")?.to_string();
|
|
|
|
let port = url.port_or_known_default().context("cannot guess port")?;
|
|
|
|
|
2020-07-15 09:37:50 +00:00
|
|
|
// Resolve the address.
|
|
|
|
let socket_addr = {
|
|
|
|
let host = host.clone();
|
2020-08-26 21:59:49 +00:00
|
|
|
smol::unblock(move || (host.as_str(), port).to_socket_addrs())
|
|
|
|
.await?
|
2020-07-15 09:37:50 +00:00
|
|
|
.next()
|
|
|
|
.context("cannot resolve address")?
|
|
|
|
};
|
|
|
|
|
2020-03-29 15:59:28 +00:00
|
|
|
// Connect to the address.
|
|
|
|
match url.scheme() {
|
|
|
|
"ws" => {
|
2020-07-15 09:37:50 +00:00
|
|
|
let stream = Async::<TcpStream>::connect(socket_addr).await?;
|
2020-03-29 15:59:28 +00:00
|
|
|
let (stream, resp) = async_tungstenite::client_async(addr, stream).await?;
|
|
|
|
Ok((WsStream::Plain(stream), resp))
|
|
|
|
}
|
|
|
|
"wss" => {
|
2020-04-26 17:37:29 +00:00
|
|
|
// In case of WSS, establish a secure TLS connection first.
|
2020-07-15 09:37:50 +00:00
|
|
|
let stream = Async::<TcpStream>::connect(socket_addr).await?;
|
2020-04-06 20:19:54 +00:00
|
|
|
let stream = tls.connect(host, stream).await?;
|
2020-03-29 15:59:28 +00:00
|
|
|
let (stream, resp) = async_tungstenite::client_async(addr, stream).await?;
|
|
|
|
Ok((WsStream::Tls(stream), resp))
|
|
|
|
}
|
|
|
|
scheme => bail!("unsupported scheme: {}", scheme),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() -> Result<()> {
|
2020-04-26 17:37:29 +00:00
|
|
|
// Initialize TLS with the local certificate.
|
2020-04-06 20:19:54 +00:00
|
|
|
let mut builder = native_tls::TlsConnector::builder();
|
2020-04-28 11:17:48 +00:00
|
|
|
builder.add_root_certificate(Certificate::from_pem(include_bytes!("certificate.pem"))?);
|
2020-04-06 20:19:54 +00:00
|
|
|
let tls = TlsConnector::from(builder);
|
|
|
|
|
2020-08-26 21:59:49 +00:00
|
|
|
smol::block_on(async {
|
2020-04-26 17:37:29 +00:00
|
|
|
// Connect to the server.
|
|
|
|
let (mut stream, resp) = connect("wss://127.0.0.1:9001", tls).await?;
|
2020-03-29 15:59:28 +00:00
|
|
|
dbg!(resp);
|
|
|
|
|
2020-04-26 17:37:29 +00:00
|
|
|
// Send a message and receive a response.
|
2020-03-29 15:59:28 +00:00
|
|
|
stream.send(Message::text("Hello!")).await?;
|
|
|
|
dbg!(stream.next().await);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-04-26 17:37:29 +00:00
|
|
|
/// A WebSocket or WebSocket+TLS connection.
|
2020-03-29 15:59:28 +00:00
|
|
|
enum WsStream {
|
2020-04-26 17:37:29 +00:00
|
|
|
/// A plain WebSocket connection.
|
2020-07-15 09:37:50 +00:00
|
|
|
Plain(WebSocketStream<Async<TcpStream>>),
|
2020-04-26 17:37:29 +00:00
|
|
|
|
|
|
|
/// A WebSocket connection secured by TLS.
|
2020-07-15 09:37:50 +00:00
|
|
|
Tls(WebSocketStream<TlsStream<Async<TcpStream>>>),
|
2020-03-29 15:59:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Sink<Message> for WsStream {
|
|
|
|
type Error = tungstenite::Error;
|
|
|
|
|
|
|
|
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
|
|
match &mut *self {
|
|
|
|
WsStream::Plain(s) => Pin::new(s).poll_ready(cx),
|
|
|
|
WsStream::Tls(s) => Pin::new(s).poll_ready(cx),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
|
|
|
|
match &mut *self {
|
|
|
|
WsStream::Plain(s) => Pin::new(s).start_send(item),
|
|
|
|
WsStream::Tls(s) => Pin::new(s).start_send(item),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
|
|
match &mut *self {
|
|
|
|
WsStream::Plain(s) => Pin::new(s).poll_flush(cx),
|
|
|
|
WsStream::Tls(s) => Pin::new(s).poll_flush(cx),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
|
|
match &mut *self {
|
|
|
|
WsStream::Plain(s) => Pin::new(s).poll_close(cx),
|
|
|
|
WsStream::Tls(s) => Pin::new(s).poll_close(cx),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Stream for WsStream {
|
|
|
|
type Item = tungstenite::Result<Message>;
|
|
|
|
|
|
|
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
|
|
|
match &mut *self {
|
|
|
|
WsStream::Plain(s) => Pin::new(s).poll_next(cx),
|
|
|
|
WsStream::Tls(s) => Pin::new(s).poll_next(cx),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|