0

I am upgrading tokio-tungstenite from 0.9 to 0.10, which no longer has the peer_addr method. I am dealing with WebSocketStream. I have tried this, which would have worked before:

use tokio_tungstenite::connect_async;

fn main() {
    async fn test() {
        println!("Hello, world!");
        let url = "wss://echo.websocket.org".to_string();

        let (ws_stream, ws_response) = connect_async(url).await.unwrap();
        let addr = ws_stream.peer_addr();
        println!("peer addr {:?}", addr);
    }
}

peer_addr() no longer exists and I can see no replacement or instructions on what to do now. I've tried searching the documentation and GitHub.

Cargo.toml:

futures = { version = "0.3" }
tungstenite = {version="0.11.0", features=["tls"] }
tokio-tungstenite = { version="0.10.1", features = ["tls"] }
tokio = {version ="0.2.21", features = [ "full" ] }
url = "2.0"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Fachtna Simi
  • 437
  • 2
  • 13

1 Answers1

1

The documentation on docs.rs is incorrect. If you build the docs locally, you'll see the correct signature of connect_async:

pub async fn connect_async<R>(
    request: R
) -> Result<(WebSocketStream<MaybeTlsStream<TcpStream>>, Response), Error> 
where
    R: IntoClientRequest + Unpin, 

You need to get to the TcpStream to get access to the peer address:

use tokio_tungstenite::{connect_async, stream::Stream};

#[tokio::main]
async fn main() {
    let (ws_stream, _) = connect_async("wss://echo.websocket.org").await.unwrap();

    let tcp_stream = match ws_stream.get_ref() {
        Stream::Plain(s) => s,
        Stream::Tls(t) => t.get_ref(),
    };

    let addr = tcp_stream
        .peer_addr()
        .expect("connected streams should have a peer address");

    println!("peer addr {:?}", addr);
}

Cargo.toml:

[dependencies]
tokio-tungstenite = { version = "0.10.1", features = ["tls"] }
tokio = { version = "0.2.21", features = [ "full" ] }

Note that your original Cargo.toml contains two different versions of tungstenite and you really don't want that. See also Why is a trait not implemented for a type that clearly has it implemented?.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    Just wanted to say that last comment you made has proven to be very helpful and has resolved other problems I was having. – Fachtna Simi Jul 22 '20 at 18:24