Last active
May 5, 2018 17:34
-
-
Save kenoss/0a20e48637e3b4ec7cee9d219c241bbf to your computer and use it in GitHub Desktop.
Working example of unix domain socket in Rust (rustc 1.26.0-beta.18); c.f. http://www.cs.brandeis.edu/~cs146a/rust/rustbyexample-02-21-2015/sockets.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// client.rs | |
use std::env; | |
use std::io::Write; | |
use std::os::unix::net::UnixStream; | |
use std::path::Path; | |
use common::SOCKET_PATH; | |
mod common; | |
fn main() { | |
let messages: Vec<String> = env::args().skip(1).map(|x| x.to_string()).collect(); | |
let socket = Path::new(SOCKET_PATH); | |
for message in messages { | |
// Connect to socket | |
let mut stream = match UnixStream::connect(&socket) { | |
Err(_) => panic!("server is not running"), | |
Ok(stream) => stream, | |
}; | |
// Send message | |
match stream.write_all(message.as_bytes()) { | |
Err(_) => panic!("couldn't send message"), | |
Ok(_) => {} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// common.rs | |
pub static SOCKET_PATH: &'static str = "loopback-socket"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// server.rs | |
use std::fs; | |
use std::io::Read; | |
use std::os::unix::net::{UnixListener, UnixStream}; | |
use std::path::Path; | |
use std::thread; | |
use common::SOCKET_PATH; | |
mod common; | |
fn main() { | |
let socket = Path::new(SOCKET_PATH); | |
// Delete old socket if necessary | |
if socket.exists() { | |
fs::remove_file(&socket).unwrap(); | |
} | |
// Bind to socket | |
let listener = match UnixListener::bind(&socket) { | |
Err(_) => panic!("failed to bind socket"), | |
Ok(listener) => listener, | |
}; | |
println!("Server started, waiting for clients"); | |
// accept connections and process them, spawning a new thread for each one | |
for stream in listener.incoming() { | |
match stream { | |
Ok(stream) => { | |
/* connection succeeded */ | |
thread::spawn(|| handle_client(stream)); | |
} | |
Err(_) => { | |
/* connection failed */ | |
break; | |
} | |
} | |
} | |
} | |
fn handle_client(mut stream: UnixStream) { | |
let mut response = String::new(); | |
stream.read_to_string(&mut response).unwrap(); | |
println!("Client said: {}", response); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment