#![allow(deprecated)]
use std::net::SocketAddr;
use anyhow::Context;
use clap::Parser;
use futures_lite::StreamExt;
use iroh_net::{
key::SecretKey,
relay::{RelayMode, RelayUrl},
Endpoint, NodeAddr,
};
use tracing::info;
const EXAMPLE_ALPN: &[u8] = b"n0/iroh/examples/magic/0";
#[derive(Debug, Parser)]
struct Cli {
#[clap(long)]
node_id: iroh_net::NodeId,
#[clap(long, value_parser, num_args = 1.., value_delimiter = ' ')]
addrs: Vec<SocketAddr>,
#[clap(long)]
relay_url: RelayUrl,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();
println!("\nconnect (unreliable) example!\n");
let args = Cli::parse();
let secret_key = SecretKey::generate();
println!("secret key: {secret_key}");
let endpoint = Endpoint::builder()
.secret_key(secret_key)
.alpns(vec![EXAMPLE_ALPN.to_vec()])
.relay_mode(RelayMode::Default)
.bind()
.await?;
let me = endpoint.node_id();
println!("node id: {me}");
println!("node listening addresses:");
for local_endpoint in endpoint
.direct_addresses()
.next()
.await
.context("no endpoints")?
{
println!("\t{}", local_endpoint.addr)
}
let relay_url = endpoint
.home_relay()
.expect("should be connected to a relay server, try calling `endpoint.local_endpoints()` or `endpoint.connect()` first, to ensure the endpoint has actually attempted a connection before checking for the connected relay server");
println!("node relay server url: {relay_url}\n");
let addr = NodeAddr::from_parts(args.node_id, Some(args.relay_url), args.addrs);
let conn = endpoint.connect(addr, EXAMPLE_ALPN).await?;
info!("connected");
let message = format!("{me} is saying 'hello!'");
conn.send_datagram(message.as_bytes().to_vec().into())?;
let message = conn.read_datagram().await?;
let message = String::from_utf8(message.into())?;
println!("received: {message}");
Ok(())
}