Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // [package]
- // name = "websocket-test"
- // version = "0.1.0"
- // authors = []
- // edition = "2018"
- // [dependencies]
- // websocket-lowlevel = {
- // git = "https://github.com/sdroege/rust-websocket.git",
- // rev = "tokio-0.2",
- // default-features = false,
- // features = ["async"]
- // }
- // futures-preview = { version = "0.3.0-alpha.19" }
- // tokio = { version = "0.2.0-alpha.6" }
- // tokio-io = { version = "0.2.0-alpha.6" }
- // hyper = { version = "0.13.0-alpha.4" }
- // hyper-tls = { version = "0.4.0-alpha.4" }
- use tokio::codec::Decoder;
- use tokio::prelude::*;
- fn main() {
- let https = hyper_tls::HttpsConnector::new().unwrap();
- let client = hyper::Client::builder().build::<_, hyper::Body>(https);
- let f = async {
- let key = websocket_lowlevel::header::WebSocketKey::new();
- let req = hyper::Request::builder()
- .uri("https://echo.websocket.org")
- .header(hyper::header::HOST, "echo.websocket.org")
- .header(hyper::header::UPGRADE, "websocket")
- .header(hyper::header::CONNECTION, "Upgrade")
- .header("Sec-WebSocket-Version", "13")
- .header("Sec-WebSocket-Key", key.serialize())
- .body(hyper::Body::empty())
- .unwrap();
- println!("req: {:?}", req);
- let res = client.request(req).await;
- println!("res: {:?}", res);
- let res = res.expect("Failed HTTP request");
- if res.status() != hyper::StatusCode::SWITCHING_PROTOCOLS {
- panic!("Not switching protocols: {}", res.status());
- }
- let headers = res.headers();
- let accept = headers
- .get("Sec-WebSocket-Accept")
- .and_then(|h| h.to_str().ok());
- if accept.is_none() {
- panic!("No Accept header");
- }
- let accept = accept.unwrap();
- let expected_accept = websocket_lowlevel::header::WebSocketAccept::new(&key);
- if expected_accept.serialize() != accept {
- panic!(
- "Accept header wrong: excepted {}, got {}",
- expected_accept.serialize(),
- accept
- );
- }
- let (mut w, r) = match res.into_body().on_upgrade().await {
- Ok(upgrade) => {
- let framed = websocket_lowlevel::codec::ws::MessageCodec::default(
- websocket_lowlevel::codec::ws::Context::Client,
- )
- .framed(upgrade);
- framed.split()
- }
- Err(err) => {
- panic!("Failed to upgrade: {:?}", err);
- }
- };
- let res = w
- .send(websocket_lowlevel::message::OwnedMessage::Text(
- "blablabla".into(),
- ))
- .await;
- res.expect("sending failed");
- let (m, r) = r.into_future().await;
- let m = m.unwrap();
- println!("msg {:?}", m);
- };
- tokio::runtime::Builder::new().build().unwrap().block_on(f);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement