forked from ryzokuken/cosmoline
Quick and dirty peer discovery broadcast mock implementation
* Use `async_std::task` for network loops * Send the generated public key over ipv4 udp broadcast frames (peer discovery is not functional yet, although multiple instances connected to the same link can now talk to each other, so yay.)
This commit is contained in:
parent
0405ec3b16
commit
2ba51c8677
42
src/main.rs
42
src/main.rs
|
@ -1,8 +1,9 @@
|
|||
use clap::{load_yaml, App};
|
||||
use ed25519_dalek::Keypair;
|
||||
use async_std::fs;
|
||||
use async_std::{fs, task};
|
||||
use async_std::net::UdpSocket;
|
||||
use async_std::path::PathBuf;
|
||||
use async_std::sync::Arc;
|
||||
|
||||
mod keypair;
|
||||
|
||||
|
@ -32,6 +33,32 @@ fn parse_packet(packet: String) -> Host {
|
|||
}
|
||||
}
|
||||
|
||||
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, parse_packet(packet)));
|
||||
}
|
||||
}
|
||||
|
||||
async fn peer_discovery_send(id: Arc<String>) {
|
||||
let socket = UdpSocket::bind(":::0").await.unwrap();
|
||||
let msg = format!("net:cosmoline:8023~shs:{}", &id);
|
||||
let buf = msg.as_bytes();
|
||||
|
||||
socket.set_broadcast(true).unwrap();
|
||||
|
||||
loop {
|
||||
println!("{:?}", ("broadcasting identity", &id));
|
||||
socket.send_to(&buf, "255.255.255.255:8008").await.unwrap();
|
||||
task::sleep(std::time::Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_std::main]
|
||||
async fn main() {
|
||||
let options = load_yaml!("options.yaml");
|
||||
|
@ -57,14 +84,9 @@ async fn main() {
|
|||
let keypair = Keypair::read_or_generate(path.join("secret")).await;
|
||||
println!("{}", keypair.to_json().pretty(2));
|
||||
|
||||
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, parse_packet(packet)));
|
||||
};
|
||||
let json_id = keypair.to_json()["id"].clone();
|
||||
let id = json_id.as_str().unwrap();
|
||||
|
||||
task::spawn(peer_discovery_recv());
|
||||
task::spawn(peer_discovery_send(Arc::new(id.to_string()))).await;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue