如何使用tungstenite库从服务器向客户端发送消息

问题描述 投票:0回答:0

我想做的是:

  1. 在另一个线程中启动 websocket 服务器,因为主线程已经被 rocket rs 阻塞了
  2. 客户端订阅此服务器。(未实现)
  3. 从服务器向客户端发送消息。 我怎样才能在火箭/主/另一个线程中做到这一点。例如。一个用户 在他的个人资料中添加了一个新的播客。此播客下载于 后台由服务器和用户应该得到多远的反馈 进程有进展

main.rs

    DB::new().unwrap();
    create_podcast_root_directory_exists();

    thread::spawn(||{
        let mut scheduler = Scheduler::new();

        scheduler.every(300.minutes()).run(||{
            let db = DB::new().unwrap();
            //check for new episodes
            let podcasts = db.get_podcasts().unwrap();
            println!("Checking for new episodes: {:?}", podcasts);
            for podcast in podcasts {
                let podcast_clone = podcast.clone();
                insert_podcast_episodes(podcast);
                schedule_episode_download(podcast_clone)
            }
        });
        loop {
            scheduler.run_pending();
            thread::sleep(Duration::from_millis(1000));
        }
    });
    rocket().launch();

insert_podcast_episodes 方法

pub fn insert_podcast_episodes(podcast: Podcast){

    let client = ClientBuilder::new().build().unwrap();
    let result = client.get(podcast.clone().rssfeed).send().unwrap();
    let bytes = result.bytes().unwrap();
    let text = String::from_utf8(bytes.to_vec()).unwrap();
    let vec = get_media_urls(&text);

    let feed = parser::parse(&*bytes).unwrap();
    for (i,item) in feed.entries.iter().enumerate(){
        let db = DB::new().unwrap();
        let mut result = db.get_podcast_episode_by_id(&item.id);

        if result.unwrap().is_none() {
            // Insert new podcast episode
            db.insert_podcast_episodes(podcast.clone(), &vec[i].to_owned(), item, &feed.logo
                .clone().unwrap().uri);
            // Tell client that new episode was downloaded via websocket
        }
    }
}

如循环末尾的评论中所述,我想向用户发送消息。我怎样才能做到这一点?有某种依赖注入吗?

rust websocket rust-tokio
© www.soinside.com 2019 - 2024. All rights reserved.