Function tokio_websockets::http::upgrade_request
source · pub fn upgrade_request<T>(uri: T) -> Result<Request<Empty<Bytes>>, Error>where
Uri: TryFrom<T>,
<Uri as TryFrom<T>>::Error: Into<Error>,
Available on crate features
http-integration
and client
only.Expand description
Create a HTTP upgrade request for use with HTTP libraries.
This can be sent with a client and then waiting for the upgrade to complete.
For example, using hyper:
use hyper::{self, client::HttpConnector, Client, StatusCode, Uri};
use tokio_websockets::{upgrade_request, ClientBuilder};
// Create a new hyper client, ideally you'd reuse an existing one
// The HTTP Connector does not allow ws:// per default
let mut connector = HttpConnector::new();
connector.enforce_http(false);
let client = Client::builder().build(connector);
let uri = Uri::from_static("ws://localhost:3333");
let response = client.request(upgrade_request(uri)?).await?;
assert!(
response.status() == StatusCode::SWITCHING_PROTOCOLS,
"Our server didn't upgrade: {}",
response.status()
);
let stream = match hyper::upgrade::on(response).await {
Ok(upgraded) => ClientBuilder::new().take_over(upgraded),
Err(e) => panic!("upgrade error: {}", e),
};
// stream is a websocket stream like any other one
Errors
This method returns a http::Error
if assembling the request failed,
which should never happen.