use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::time::Duration; use futures_util::StreamExt; use tokio::sync::Mutex; use tokio_tungstenite::tungstenite::Message; use tracing::trace; use exchanges::binance_spot_ws::{BinanceSpotLogin, BinanceSpotSubscribeType, BinanceSpotWs, BinanceSpotWsType}; use exchanges::socket_tool::AbstractWsMode; // 账号密码 const ACCESS_KEY: &str = ""; const SECRET_KEY: &str = ""; //ws-订阅公共频道信息 #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn ws_custom_subscribe() { global::log_utils::init_log_with_trace(); let (write_tx, write_rx) = futures_channel::mpsc::unbounded(); let (read_tx, mut read_rx) = futures_channel::mpsc::unbounded(); let login_param = BinanceSpotLogin { api_key: ACCESS_KEY.to_string(), api_secret: SECRET_KEY.to_string(), }; let mut ws = get_ws(None); ws.set_symbols(vec!["BTC_USDT".to_string()]); ws.set_subscribe(vec![ // BinanceSpotSubscribeType::PuBookTicker, // BinanceSpotSubscribeType::PuAggTrade, BinanceSpotSubscribeType::PuDepth20levels100ms, ]); let write_tx_am = Arc::new(Mutex::new(write_tx)); let is_shutdown_arc = Arc::new(AtomicBool::new(true)); //读取 let _is_shutdown_arc_clone = Arc::clone(&is_shutdown_arc); let _tr = tokio::spawn(async move { trace!("线程-数据读取-开启"); loop { if let Some(data) = read_rx.next().await { trace!("读取数据data:{:?}",data) } } // trace!("线程-数据读取-结束"); }); //写数据 // let bool_v2_clone = Arc::clone(&is_shutdown_arc); // let write_tx_clone = Arc::clone(&write_tx_am); // let su = ws.get_subscription(); // let tw = tokio::spawn(async move { // trace!("线程-数据写入-开始"); // loop { // tokio::time::sleep(Duration::from_millis(20 * 1000)).await; // // let close_frame = CloseFrame { // // code: CloseCode::Normal, // // reason: Cow::Borrowed("Bye bye"), // // }; // // let message = Message::Close(Some(close_frame)); // // // let message = Message::Text(su.clone()); // AbstractWsMode::send_subscribe(write_tx_clone.clone(), message.clone()).await; // trace!("发送指令成功"); // } // trace!("线程-数据写入-结束"); // }); let t1 = tokio::spawn(async move { //链接 let bool_v3_clone = Arc::clone(&is_shutdown_arc); ws.ws_connect_async(bool_v3_clone, &write_tx_am, write_rx, read_tx).await.expect("链接失败(内部一个心跳线程应该已经关闭了)"); trace!("test 唯一线程结束--"); }); tokio::try_join!(t1).unwrap(); trace!("当此结束"); trace!("重启!"); trace!("参考交易所关闭"); return; } fn get_ws(login_param: Option) -> BinanceSpotWs { let binance_ws = BinanceSpotWs::new(false, login_param, BinanceSpotWsType::PublicAndPrivate, ); binance_ws }