Move the peer discovery send/recv tasks to the network module

This commit is contained in:
mirsal 2021-04-01 11:08:45 +00:00
parent 52862bbace
commit 48c2270f3a
2 changed files with 36 additions and 36 deletions

View File

@ -1,5 +1,4 @@
use async_std::{fs, task};
use async_std::net::UdpSocket;
use async_std::path::PathBuf;
use async_std::sync::Arc;
use clap::{load_yaml, App};
@ -9,41 +8,9 @@ mod keypair;
use keypair::{SSBKeypair, SSBPublicKey};
mod network;
use network::Peer;
type Config = toml::map::Map<String, toml::Value>;
async fn peer_discovery_recv() {
let socket = UdpSocket::bind(":::8008").await.unwrap();
let mut buf = [0u8; 1024];
loop {
let (amt, peer) = socket.recv_from(&mut buf).await.unwrap();
let buf = &mut buf[..amt];
let packet = String::from_utf8(buf.to_vec()).unwrap();
println!(
"{} {}",
peer,
Peer::from_discovery_packet(&packet).to_discovery_packet()
);
}
}
async fn peer_discovery_send(pubkey: Arc<String>) {
let socket = UdpSocket::bind(":::0").await.unwrap();
let msg = format!("net:1.2.3.4:8023~shs:{}", &pubkey);
let buf = msg.as_bytes();
socket.set_broadcast(true).unwrap();
loop {
println!("Sending packet: {:?}", &msg);
socket.send_to(&buf, "255.255.255.255:8008").await.unwrap();
socket.send_to(&buf, "[FF02::1]:8008").await.unwrap();
task::sleep(std::time::Duration::from_secs(1)).await;
}
}
#[async_std::main]
async fn main() {
let options = load_yaml!("options.yaml");
@ -73,6 +40,6 @@ async fn main() {
let pubkey = keypair.public.to_base64();
task::spawn(peer_discovery_recv());
task::spawn(peer_discovery_send(Arc::new(pubkey))).await;
task::spawn(network::peer_discovery_recv());
task::spawn(network::peer_discovery_send(Arc::new(pubkey))).await;
}

View File

@ -1,4 +1,6 @@
use async_std::net::IpAddr;
use async_std::task;
use async_std::net::{IpAddr, UdpSocket};
use async_std::sync::Arc;
use ed25519_dalek::PublicKey;
use crate::keypair::SSBPublicKey;
@ -58,3 +60,34 @@ impl Peer {
}
}
}
pub async fn peer_discovery_recv() {
let socket = UdpSocket::bind(":::8008").await.unwrap();
let mut buf = [0u8; 1024];
loop {
let (amt, peer) = socket.recv_from(&mut buf).await.unwrap();
let buf = &mut buf[..amt];
let packet = String::from_utf8(buf.to_vec()).unwrap();
println!(
"{} {}",
peer,
Peer::from_discovery_packet(&packet).to_discovery_packet()
);
}
}
pub async fn peer_discovery_send(pubkey: Arc<String>) {
let socket = UdpSocket::bind(":::0").await.unwrap();
let msg = format!("net:1.2.3.4:8023~shs:{}", &pubkey);
let buf = msg.as_bytes();
socket.set_broadcast(true).unwrap();
loop {
println!("Sending packet: {:?}", &msg);
socket.send_to(&buf, "255.255.255.255:8008").await.unwrap();
socket.send_to(&buf, "[FF02::1]:8008").await.unwrap();
task::sleep(std::time::Duration::from_secs(1)).await;
}
}