rust中Arc使用有点问题?

新手上路,请多包涵
use bitunix::{run};
use ws::{connect, CloseCode, Sender};
use std::borrow::Borrow;
use std::f64::consts;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use serde_json;
use std::thread;
use time;
mod websocket;
use websocket::sub_channel::SubChannel;
use std::rc::Rc;
use std::sync::{Mutex, Arc};
fn main() {
    run();
    if let Err(error) = connect("ws://zengwe.xyz/ws-futures/?from=contract&compress=0", |out| {
        let out = Arc::new(Mutex::new(out));
        // {
        //     let out = Arc::clone(&out);
        //     thread::spawn(move || loop {
        //         thread::sleep(Duration::from_secs(3));
        //         print!("send msg!\n");
        //         if let Err(e) = out.lock().unwrap().send(format!("{{\"ping\": {:?}}}", time::get_time().sec)) {
        //             println!("Error sending a periodic message: {:?}", e);
        //         }
        //     });
        // }

        // thread::sleep(Duration::from_secs(3));
        let mark_price_channel = SubChannel::new("mark_price_btcusdt");
        
        let send_msg = serde_json::to_string(&mark_price_channel).unwrap();
        print!("{:?}", send_msg);
        // // out.lock().unwrap().send(send_msg);
        {
            let out = Arc::clone(&out);
            let temp_out = out.lock().unwrap();
            temp_out.send(send_msg);
        }

        move |msg| {
            // 处理在此连接上接收的消息
            println!("Client 收到消息 '{}'. ", msg);
            // out.send("'{\"pong\":1705631243}").unwrap();
            // 关闭连接
            // out.close(CloseCode::Normal);
            return Ok(());
        }
    }) {
        // 通知用户故障
        println!("Failed to create WebSocket due to: {:?}", error);
    }
}
     let out = Arc::clone(&out);
        let temp_out = out.lock().unwrap();
        temp_out.send(send_msg);都会报错(Encountered an error: not connected)

删除这里在前面的线程中是可以循环send消息的
求大佬帮助!
这里不管怎么改调用send

1.在这里Arc::clone试过不行
2.sleep一会儿还是不行
刚开始学,rust有点难,还没入门提的问题可能有点弱鸡,望各位大佬能提点一下

阅读 497
avatarAI BotBETA

根据你提供的代码,问题可能出在多个地方。首先,让我们先理解一下你的代码的逻辑。

在代码中,你创建了一个WebSocket连接,并使用ArcMutexout进行了封装,以便在多个线程中共享和修改它。然后,你尝试通过这个WebSocket连接发送消息。

关于你的问题,报错“Encountered an error: not connected”可能是由于以下原因:

  1. WebSocket连接未建立完成:在尝试发送消息之前,需要确保WebSocket连接已经完全建立并且已经成功连接到服务器。你可以尝试在发送消息之前添加一些延时,或者使用其他方法来确保连接已经建立完成。
  2. 线程安全问题:由于你使用了ArcMutexout进行了封装,你需要确保在发送消息时对out的访问是线程安全的。你需要确保每次只有一个线程访问和修改out
  3. WebSocket连接关闭:在尝试发送消息时,如果WebSocket连接已经关闭,那么将会出现“Encountered an error: not connected”的错误。你需要确保在发送消息之前检查WebSocket连接的状态,并处理可能的关闭情况。

为了解决这些问题,你可以尝试以下方法:

  1. 在发送消息之前添加一些延时,以确保WebSocket连接已经建立完成。
  2. 使用Mutexout进行线程安全访问,确保只有一个线程同时访问和修改out
  3. 在尝试发送消息之前检查WebSocket连接的状态,并处理可能的关闭情况。

下面是一个示例代码片段,其中添加了一些延时和检查WebSocket连接状态的逻辑:

use std::time::Duration;
use websocket::{Message, Result};

// ... 其他代码 ...

let out = Arc::new(Mutex::new(out));
let temp_out = out.lock().unwrap();
let send_msg = serde_json::to_string(&mark_price_channel).unwrap();
print!("{:?}", send_msg);

// 延时一段时间以确保WebSocket连接建立完成
thread::sleep(Duration::from_secs(3));

if let Err(e) = temp_out.send(Message::Text(send_msg)) {
    if let Err(e) = temp_out.send(Message::Ping(vec![])) {
        println!("Error sending a message: {:?}", e);
    } else {
        println!("Sent ping to keep the connection alive");
    }
} else {
    println!("Sent message: {}", send_msg);
}

请注意,这只是一个示例代码片段,并不能保证完全解决你的问题。你需要根据你的具体情况进行调整和修改。同时,建议仔细阅读相关的文档和资料,以便更好地理解Rust中的并发和线程安全编程。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进