Skip to content

Instantly share code, notes, and snippets.

@kenoss
Last active May 5, 2018 17:34
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 kenoss/0a20e48637e3b4ec7cee9d219c241bbf to your computer and use it in GitHub Desktop.
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
// 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(_) => {}
}
}
}
// common.rs
pub static SOCKET_PATH: &'static str = "loopback-socket";
// 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