Unix socket programming

#1

i’m write simple unixstream socket client and server side
this client side code

use std::os::unix::net::UnixStream;
use std::io::prelude::*;

fn main() {
    let mut stream = UnixStream::connect("/tmp/socket").unwrap();
    stream.write_all(b"hello i'm client side").unwrap();
    let mut buf = String::new();
    stream.read_to_string(&mut buf).unwrap();
    println!("{}", buf);
}

and server side code

use std::io::prelude::*;
use std::os::unix::net::{UnixListener, UnixStream};
use std::thread;

fn handle_client(mut stream: UnixStream) {
    let mut buf = [0; 1024];// let mut buf = String::new();
    stream.read(&mut buf).unwrap();// stream.read_to_string(&mut buf).unwrap();
    stream.flush().unwrap();
    // println!("{}", buf);
    println!("{}", std::str::from_utf8(&buf).unwrap());
    stream.write(b"hello i'm server").unwrap();
}

fn main() {
    let listener = UnixListener::bind("/tmp/socket").unwrap();
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(|| handle_client(stream));
            }
            Err(_) => {
                break;
            }
        }
    }
}

in server side code if i use buffer (variable buf in handle_client function) as array u8 it every things is Ok but if use buffer as type String (replace comments) program not work why ?
i’m sorry for newbie question and bad english

#2

read_to_string “Read all bytes until EOF”
Your link shutsdown one way but not the other. Have to add it explicitly if requiring such behaviour.

1 Like
#3

thank you