Skip to content

Instantly share code, notes, and snippets.

@DerekV
Created September 19, 2016 13:16
Show Gist options
  • Save DerekV/627de88279e2c0e44ec9a584ef870029 to your computer and use it in GitHub Desktop.
Save DerekV/627de88279e2c0e44ec9a584ef870029 to your computer and use it in GitHub Desktop.
Example of sending data over local network in rust
use std::thread;
use std::io;
use std::io::prelude::*;
use std::time::Duration;
use std::net::{TcpListener, TcpStream};
use std::fs::File;
fn handle_client(mut stream: TcpStream) -> io::Result<File> {
let buf: &mut [u8; 100] = &mut [0; 100];
let mut file = try!(File::create("foo"));
loop {
let result = stream.read(buf);
match result {
Ok(len) => {
let str = String::from_utf8(buf[0..len].to_vec());
let _ = try!(file.write_all(&buf[0..len]));
println!("wrote: {:?}", str);
},
Err(e) => {
println!("error parsing header: {:?}", e);
return Err(e);
}
}
}
}
fn main() {
println!("Hello, world!");
thread::spawn(move || {
let listener = TcpListener::bind("127.0.0.1:34234").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
// connection succeeded
handle_client(stream)
});
}
Err(_) => { /* connection failed */ },
}
}
});
let mut client = TcpStream::connect("127.0.0.1:34234").unwrap();
match client.write(b"I'm a teapot!") {
Ok(len) => println!("wrote {} bytes", len),
Err(e) => println!("error parsing header: {:?}", e)
}
thread::sleep(Duration::new(1,0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment