argmin_observer_spectator/
sender.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use futures::SinkExt;
9use spectator::Message;
10use tokio::net::TcpStream;
11use tokio_util::codec::{Framed, LengthDelimitedCodec};
12
13#[tokio::main(flavor = "current_thread")]
14pub(crate) async fn sender(
15    mut rx: tokio::sync::mpsc::Receiver<Message>,
16    host: String,
17    port: u16,
18) -> Result<(), anyhow::Error> {
19    let codec = LengthDelimitedCodec::new();
20    if let Ok(stream) = TcpStream::connect(format!("{host}:{port}")).await {
21        let mut stream = Framed::new(stream, codec);
22        while let Some(msg) = rx.recv().await {
23            stream.send(msg.pack()?).await?;
24            if let Message::Termination { .. } = msg {
25                return Ok(());
26            }
27        }
28    } else {
29        eprintln!("Can't connect to spectator on {host}:{port}");
30    }
31    Ok(())
32}