Skip to content

Instantly share code, notes, and snippets.

@jasperla
Created January 18, 2020 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasperla/ea594a27fe83df88c486fb44b7a352db to your computer and use it in GitHub Desktop.
Save jasperla/ea594a27fe83df88c486fb44b7a352db to your computer and use it in GitHub Desktop.
use std::io::prelude::*;
use std::net::TcpStream;
use crossbeam_channel::{unbounded, Receiver, Sender};
use crossbeam_utils::thread;
use rand::prelude::*;
use std::time::Duration;
pub type Msg = Box<u8>;
#[derive(Debug, PartialEq)]
pub enum Command {
Hello,
Bye,
}
#[derive(Debug)]
pub struct Client {
pub username: String,
pub cmd_s: Sender<Command>,
pub msg_r: Receiver<Msg>,
}
#[derive(Debug)]
pub struct Server {
hostname: String,
sock: TcpStream,
cmd_r: Receiver<Command>,
msg_s: Sender<Msg>,
}
impl Server {
fn new(hostname: &str, cmd_r: Receiver<Command>, msg_s: Sender<Msg>) -> Server {
let sock = TcpStream::connect(format!("{}:44444", hostname)).unwrap();
Server {
hostname: hostname.to_string(),
cmd_r: cmd_r,
msg_s: msg_s,
sock: sock,
}
}
fn recv(&self) -> Msg {
Box::new(random())
}
fn send(&mut self, message: Box<[u8]>) -> std::io::Result<()> {
self.sock.write(&message)?;
Ok(())
}
pub fn run(&self) {
thread::scope(|s| {
s.spawn(|_| loop {
match self.cmd_r.try_recv() {
Ok(m) if m == Command::Bye => {
println!("Terminating connection to remote host");
self.send(Box::new([0x1, 0x2, 0x3])).unwrap();
},
Ok(m) => println!("cmd_r: read: {:?}", m),
Err(_) => {}, //println!("cmd_r: nothing came in"),
}
let msg = self.recv();
self.msg_s.send(msg.clone()).unwrap();
println!("msg_s: sent {}", msg);
std::thread::sleep(Duration::from_secs(1));
});
})
.unwrap();
}
}
pub fn init(hostname: &str, username: &str) -> (Client, Server) {
let (msg_s, msg_r) = unbounded();
let (cmd_s, cmd_r) = unbounded();
let server = Server::new(hostname, cmd_r, msg_s);
let client = Client {
username: username.to_string(),
cmd_s: cmd_s,
msg_r: msg_r,
};
(client, server)
}
fn main() {
let (client, server) = init("127.0.0.1", "jasperla");
println!("Entering thread loop from client");
thread::scope(|s| {
s.spawn(|_| {
server.run();
});
s.spawn(|_| loop {
match client.msg_r.try_recv() {
Ok(m) => println!("msg_r: read: {:?}", m),
Err(_) => {},
}
println!("cmd_s: Sending Hello");
client.cmd_s.send(Command::Hello).unwrap();
std::thread::sleep(Duration::from_secs(1));
println!("cmd_s: Sending Bye");
client.cmd_s.send(Command::Bye).unwrap();
});
})
.unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment