Skip to content

Instantly share code, notes, and snippets.

@GRAYgoose124
Created November 11, 2021 05:04
Show Gist options
  • Select an option

  • Save GRAYgoose124/94281ce087472cd53d1422dbc9e9ded8 to your computer and use it in GitHub Desktop.

Select an option

Save GRAYgoose124/94281ce087472cd53d1422dbc9e9ded8 to your computer and use it in GitHub Desktop.
// peers.rs
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use itertools::Itertools;
pub struct Peer {
pub buffer: [u8; 256],
server: TcpListener,
clients: Vec<TcpStream>,
}
impl Peer {
pub fn new(port: u32) -> Self {
let localhost = "localhost:".to_string() + &port.to_string();
let listener = TcpListener::bind(localhost).unwrap();
Peer {
buffer: [0; 256],
server: listener,
clients: Vec::new(),
}
}
// parse_addr dict indexing?
pub fn add_peer(&mut self, peer: String) {
let stream = TcpStream::connect(peer);
match stream {
Ok(stream) => {
self.clients.push(stream);
}
Err(_e) => {}
}
}
pub fn tick(&mut self) { // TODO: 2 threads
for mut client in &self.clients {
client.write(&[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 10]);
}
match self.server.accept() {
Ok((mut stream, _addr)) => { stream.read(self.buffer.as_mut()); },
Err(_e) => {}
}
}
}
fn parse_address(address: String) -> (String, u32) {
let (addr, port) = address.splitn(2, ":").collect_tuple().unwrap();
return (addr.to_string(), port.parse::<u32>().unwrap());
}
// main.rs
#![feature(in_band_lifetimes)]
use std::env;
use std::thread;
use std::thread::sleep;
use std::time::Duration;
mod peer;
mod sandbox;
use crate::peer::Peer;
const NPEERS: usize = 2;
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
// peer network
let mut clients = vec![];
for i in 0..NPEERS {
clients.push(Peer::new(9660 + i as u32));
}
for i in 0..NPEERS {
for j in 0..NPEERS {
if i == j { continue }
let p2 = 9660 + j as u32;
clients[i].add_peer("localhost:".to_string() + &p2.to_string());
}
}
// debug peer
let mut host = Peer::new(9667);
for i in 0..NPEERS {
host.add_peer("localhost:".to_string() + &(9660 + i as u32).to_string());
clients[i].add_peer("localhost:9667".to_string());
}
// test threading
let mut threads = vec![];
for i in 0..NPEERS {
let mut c = clients.pop().unwrap();
threads.push(thread::spawn(move ||
loop {
c.tick();
sleep(Duration::from_millis(50));
}));
}
loop {
host.tick();
print!("DBG: {:?}", host.buffer);
sleep(Duration::from_millis(50));
}
for t in threads {
// Wait for the thread to finish. Returns a result.
let _ = t.join();
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment