Question on using tokio_tungstenite and futures

Hi there, I'm trying to write a WebSocket client to collect data for myself. In the following code, I send 2 heartbeats but only get 1 in the while let part. Did I do something wrong?

use futures::channel;
use futures_util::StreamExt;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};

#[tokio::main]
async fn main() {
    let connet_address = "wss://stream.bybit.com/realtime";
    let url = url::Url::parse(connet_address).unwrap();

    let (tx, rx) = channel::mpsc::unbounded::<Message>();
    let _heartbeat_handles = tokio::spawn(send_heartbeat(tx));

    let (ws_stream, response) = connect_async(url).await.expect("Failed connect");
    println!("WebSocket handshake has been completed");
    println!("{}", response.status());

    let (write, mut read) = ws_stream.split();

    tokio::spawn(rx.map(Ok).forward(write));

    while let Some(message) = read.next().await {
        match message {
            Ok(msg) => println!("{} 1", msg),
            Err(e) => println!("{}", e),
        }
    }
}

async fn send_heartbeat(tx: channel::mpsc::UnboundedSender<Message>) {
    for i in 1..3 {
        let ping = r#"{"op":"ping"}"#.to_string();
        println!("{}, {}", i, ping);
        let send_message_result = tx.unbounded_send(Message::Text(ping));
        match send_message_result {
            Ok(_) => println!("Send ping successfully"),
            Err(e) => println!("{:?}", e),
        }
    }
}

Thanks in advance

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.