Last active
March 12, 2017 22:25
-
-
Save anxiousmodernman/8634d3ac0f688a87aafc8596998fb29b to your computer and use it in GitHub Desktop.
Reading JSON from Unix domain 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
extern crate unix_socket; | |
extern crate serde_json; | |
use serde_json::Value; | |
use std::thread; | |
use std::io::{Cursor, BufRead, BufReader}; | |
use unix_socket::{UnixStream, UnixListener}; | |
fn handle_client(mut stream: UnixStream) { | |
let mut cursor = BufReader::new(stream); | |
let mut s = String::new(); | |
let res = cursor.read_line(&mut s); | |
match res { | |
Err(_) => { | |
println!("something freaky is happening"); | |
} | |
Ok(x) => { | |
println!("read {} bytes", x); | |
println!("{}", s); | |
} | |
} | |
} | |
#[derive(Debug)] | |
struct Message<T> { | |
message_type: String, | |
payload: T | |
} | |
fn main() { | |
let listener = UnixListener::bind("/tmp/coleman-shell.sock").unwrap(); | |
// 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(err) => { | |
/* connection failed */ | |
println!("{}", err); | |
break; | |
} | |
} | |
} | |
// close the listener socket | |
drop(listener); | |
} |
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
shell.AddCmd(&ishell.Cmd{ | |
Name: "tell", | |
Help: "tell the server something", | |
Func: func(c *ishell.Context) { | |
// This is a snippet from a shell command. | |
conn, err := net.Dial("unix", socket) | |
if err != nil { | |
c.Println("error: no server listening") | |
return | |
} | |
msg := Message{"TELL", []byte(strings.Join(c.Args, " "))} | |
data, err := json.Marshal(msg) | |
if err != nil { | |
c.Println("ERROR: could not marshal json message") | |
} | |
n, err := conn.Write(data) | |
if err != nil { | |
log.Println("you can't write bytes here") | |
} | |
c.Printf("wrote %v bytes\n", n) | |
// The rust server requires that I explicitly write a newline. | |
n, err = conn.Write([]byte("\n")) | |
if err != nil { | |
log.Println("you can't write a newline") | |
} | |
c.Printf("wrote %v bytes\n", n) | |
// I get exactly 1 byte reply from the rust server. What is this? | |
b, err := ioutil.ReadAll(conn) | |
if err != nil { | |
c.Printf("error reading: %v\n", err) | |
} | |
c.Printf("read %v bytes\n", n) | |
c.Println(string(b)) | |
}, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment